博客> NSObject+LHKVO (简化kvo调用)
NSObject+LHKVO (简化kvo调用)
2小时前 评论:0 阅读:1021 lleihai123
ios kvo 每日瑜伽

NSObject+LHKVO.h

import

typedef void (^LHHandler) (); @interface NSObject (LXD_KVO)

  • (void)LHaddObserver: (NSString *)key withBlock: (LHHandler)observedHandler;
  • (void)LHremoveObserver: (NSString *)key; @end

NSObject+LHKVO.m

import "NSObject+LHKVO.h"

import

@interface NSObject (LHKVO) @property (nonatomic) NSMutableDictionary keyMumdict; @end @implementation NSObject (LHKVO) @dynamic keyMumdict; -(NSMutableDictionary)keyMumdict{ NSMutableDictionary *mudict = objc_getAssociatedObject(self, _cmd); if (!mudict) { objc_setAssociatedObject(self, _cmd, [NSMutableDictionary new], OBJC_ASSOCIATION_RETAIN_NONATOMIC); } return objc_getAssociatedObject(self, _cmd); }

-(void)LHaddObserver: (NSString *)key withBlock: (LHHandler)observedHandler{ [self.keyMumdict setObject:observedHandler forKey:key]; [self addObserver:self forKeyPath:key options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL]; }

-(void)observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionary )change context:(void *)context { LHHandler hander = [self.keyMumdict objectForKey:keyPath]; if(hander){ hander(); } }

  • (void)LHremoveObserver: (NSString *)key{ [self.keyMumdict removeObjectForKey:key]; [self removeObserver:self forKeyPath:key]; }
  • (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{

    NSArray *selStringsArray = @[@"dealloc"];
    
    [selStringsArray enumerateObjectsUsingBlock:^(NSString *selString, NSUInteger idx, BOOL *stop) {
        NSString *mySelString = [@"sd_" stringByAppendingString:selString];
    
        Method originalMethod = class_getInstanceMethod(self, NSSelectorFromString(selString));
        Method myMethod = class_getInstanceMethod(self, NSSelectorFromString(mySelString));
        method_exchangeImplementations(originalMethod, myMethod);
    }];

    }); } -(void)sd_dealloc{ NSArraykeys = [self.keyMumdict allKeys]; for (NSStringkey in keys) { [self LHremoveObserver:key]; NSLog(@"dealloc_key:%@",key); }

} @end

使用 -(void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event{ LHObservedObject*object = [LHObservedObject new]; [object LHaddObserver:@"num" withBlock:^{ NSLog(@"num"); }]; [object LHaddObserver:@"observedNum" withBlock:^{ NSLog(@"observedNum"); }]; [object LHaddObserver:@"printBlock" withBlock:^{ NSLog(@"printBlock"); }]; object.num = 0; object.observedNum = @(1); object.printBlock = ^(){}; }

源码:https://github.com/lleihai123/LHKVO/blob/master/LHKVO/ViewController.m

收藏
1
sina weixin mail 回到顶部