AIMObservers 0.3

AIMObservers 0.3

测试已测试
语言语言 Obj-CObjective C
许可证 MIT
发布最后发布2015年12月

Maciej Gad维护。



 
依赖项
AIMObserver~> 0.3
AIMNotificationObserver~> 0.3
 

AIM团队使用的通知和KVO观察者

AIMNotificationObserver是一个通知观察者,应作为以下内容的替代:[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNotification:) name:name object:sender]AIMObserver是一个KVO观察者,应作为以下内容的替代:[obj addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld|NSKeyValueObservingOptionInitial context:NULL];。当对象被释放时,保证观察者会被移除。

使用方法

NSNotificationCenter观察者

@interface ViewController ()
@property (strong, nonatomic) AIMNotificationObserver *observer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    __weak __typeof(self) weakSelf = self;
    self.observer = [AIMNotificationObserver observeName:@"changeBackground" onChange:^(NSNotification *notification) {
        //use weakSelf to avoid strong reference cycles
        weakSelf.view.backgroundColor = [UIColor red];
    }];
}

@end

KVO观察者

@interface ViewController ()
@property (strong, nonatomic) AIMObserver *observer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    __weak __typeof(self) weakSelf = self;
    self.observer = [AIMObserver observed:self.view.layer keyPath:@"backgroundColor" onChange:^(NSDictionary *change) {
        //use weakSelf to avoid strong reference cycles
        [weakSelf.button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    }];
}

@end

安装

使用CocoaPods

添加到您的Podfile中:

pod 'AIMObservers'

然后调用:

pod install

并导入:

#import "AIMNotificationObserver.h"

#import "AIMObserver.h"

示例

在该示例中,使用AIMNotificationObserver更改主视图的背景,作为对通知的响应,并使用AIMObserver在背景更改时更改按钮文本颜色(这是一个相当简单的使用方式,但在实际应用程序中,您可以以更复杂的方式使用通知和KVO)。