AIMObserver 0.3

AIMObserver 0.3

测试测试过的
语言编程语言 Obj-CObjective C
许可证 MIT
发布时间最后发布2015 年 12 月

Maciej Gad 维护。



AIMObservers

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)。