ObserverKit 1.2.0

ObserverKit 1.2.0

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

pompopo 维护。



  • pompopo

一个用于使用 UIControl, NSNotification, 键值观察等的简单库...

安装

使用 CocoaPod

pod 'ObserverKit'

#import "OKObserver.h"
#import "NSObject+OKObserver.h" // Optional

示例

self.ok_observer.control(self.field1, UIControlEventEditingChanged, ^(typeof (self) me, UITextField *field) {
    me.i = [field.text integerValue];

}).control(self.field2, UIControlEventEditingChanged, ^(typeof(self)me, UITextField *field) {
    me.j = [field.text integerValue];

}).keyPath(@[@"i", @"j"], ^(typeof(self)me, id newValue, id oldValue, NSString *path) {
    NSLog(@"%@: %@ -> %@", path, oldValue, newValue);
    me.total = me.i + me.j;

}).keyPath(@"total", ^(typeof(self)me, id val){
    me.resultLabel.text = [NSString stringWithFormat:@"%ld", [val integerValue]];

}).notification(UIApplicationDidReceiveMemoryWarningNotification, ^{
    NSLog(@"Did receive memory warning");
});

键值观察

// single key
self.ok_observer.keyPath(@"i", ^(typeof(self)me, id newValue, id oldValue) {
    NSLog(@"%@ -> %@", newValue, oldValue);
});

// multiple keys
self.ok_observer.keyPath(@[@"i", @"j"], ^(typeof(self)me, id newValue, id oldValue, NSString *keyPath) {
    if ([keyPath isEqualToString:@"i"]) {
        NSLog(@"i changed");
    } else {
        NSLog(@"j changed");
    }
});

// cast NSNumber, NSValue
self.ok_observer.keyPath(@"i", ^(typeof(self)me, NSInteger newValue) {
    // You don't have to write [newValue integerValue]
    if (newValue == 100) {
        ...
    }
});

UIControl

// single control
self.ok_observer.control(self.button, UIControlEventTouchUpInside, ^(typeof(self)me, UIButton *button, UIEvent *event) {
    NSLog(@"button touched");
});

// multiple controls
self.ok_observer.control(@[self.buttonA, self.buttonB], UIControlEventTouchUpInside, ^(typeof(self)me, UIButton *button) {
    if (button.tag == 1) {
        NSLog(@"buttonA touched");
    } else {
        NSLog(@"buttonB touched");
    }
});

// You can omit UIControlEvents with control2
self.ok_observer.control2(self.button, ^(typeof(self)me, UIButton *button, UIEvent *event) {
    NSLog(@"button touched");
});

NSNotification

// single notification
self.ok_observer.notification(UIApplicationDidReceiveMemoryWarningNotification, ^(id me, NSNotification *notification) {
    NSLog(@"memory warning");
});

// multiple notifications
self.ok_observer.notification(@[UIKeyboardDidShowNotification, UIKeyboardDidHideNotification], ^{
    NSLog(@"Keyboard did show or hide");
});

dealloc

您必须在 dealloc 中停止观察,

- (void)dealloc {
  [self ok_stop];
}

许可证

MIT 许可证。请参阅 LICENSE。