KVO

作者: foolish_hungry | 来源:发表于2018-06-14 17:15 被阅读0次

    优雅地使用KVO

    FaceBook KVOController
    使用 KVOController 进行键值观测可以说完美地解决了在使用原生 KVO 时遇到的各种问题。

    1. 不需要手动移除观察者
    2. 实现 KVO 与事件发生处的代码上下文相同,不需要跨方法传参数;
    3. 使用 block 来替代方法能够减少使用的复杂度,提升使用 KVO 的体验;
    4. 每一个 keyPath 会对应一个属性,不需要在 block 中使用 if 判断 keyPath;
    @interface ViewController ()
    
    @property (nonatomic, strong) Fizz *fizz;
    
    @end
    
    // 在viewDidLoad 中写入
    [self.KVOController observe:self.fizz
                        keyPath:@"number"
                        options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
                          block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString    *,id> * _Nonnull change) {
                              NSLog(@"%@", change);
                          }];
    

    [KVOController 源码分许] (https://draveness.me/kvocontroller)

    objc 中国 KVO and KVC

    KVO 原理

    注意点:

    我们也要指出有些集合是不能被观察的。KVO 旨在观察关系 (relationship) 而不是集合。我们不能观察 NSArray,我们只能观察一个对象的属性——而这个属性有可能是 NSArray。举例说,如果我们有一个 ContactList 对象,我们可以观察它的 contacts 属性。但是我们不能向要观察对象的 -addObserver:forKeyPath:... 传入一个 NSArray。
    相似地,观察 self 不是永远都生效的。而且这不是一个好的设计。

    • 通过runtime特性实现KVO
    • 当你观察一个对象时,一个新的类会动态被创建。这个类继承自该对象的原本的类,并重写了被观察属性的 setter 方法。自然,重写的 setter 方法会负责在调用原 setter 方法之前和之后,通知所有观察对象值的更改。最后把这个对象的 isa 指针 ( isa 指针告诉 Runtime 系统这个对象的类是什么 ) 指向这个新创建的子类,对象就神奇的变成了新创建的子类的实例。
    • 举个例子, 如果原类为Person, 那么它生成的派生类为NSKVONotifying_Person
    • 每个类对象中都有一个isa指针, 当类对象第一次被观察时, 系统会将isa指针, 指向动态生成的派生类, 从而在调用setter方法时, 调用的是派生类的setter方法.
    • 键值观察通知机制, 依赖于NSObject的两个方法, 在被观察对象属性改变之前, 会调用willChangeValueForKey: 方法, 记录旧值, 在被观察对象属性改变之后, 会调用didChangeValueForKey: 方法, 记录新值, 继而会调用 observeValueForKey:ofObject:change:context:

    原来,这个中间类,继承自原本的那个类。不仅如此,Apple 还重写了 -class 方法,企图欺骗我们这个类没有变,就是原本那个类。

    image.png

    手动写一个KVO

    1. 首先,我们创建 NSObject 的 Category,并在头文件中添加两个 API:
    #import <Foundation/Foundation.h>
    
    typedef void(^TYObservingBlock)(id observedObject, NSString *observedKey, id oldValue, id newValue);
    
    @interface NSObject (KVO)
    
    - (void)TY_addObserver:(NSObject *)observer
                    forKey:(NSString *)key
                 withBlock:(TYObservingBlock)block;
    
    - (void)TY_removeObserver:(NSObject *)observer forKey:(NSString *)key;
    
    @end
    
    1. 实现 TY_addObserver: forKey: withBlock:
    • 检查对象的类有没有相应的 setter 方法。如果没有抛出异常;
    //1. 检查对象的类有没有相应的 setter 方法。如果没有抛出异常;
        SEL setterSelctor = NSSelectorFromString(setterForGetter(key));
        Method setterMethod = class_getInstanceMethod([self class], setterSelctor);
        
        if (!setterMethod) {
            // 抛出异常
            NSString *reason = [NSString stringWithFormat:@"Object %@ does not have a setter for key %@", self, key];
            NSException *exception = [NSException exceptionWithName:NSInvalidArgumentException reason:reason userInfo:nil];
            @throw exception;
            return;
        }
    

    第一步里,先通过 setterForGetter() 方法获得相应的 setter 的名字(SEL)。也就是把 key 的首字母大写,然后前面加上 set 后面加上 :,这样 key 就变成了 setKey:。然后再用 class_getInstanceMethod 去获得 setKey: 的实现(Method)。如果没有,自然要抛出异常。

    • 检查对象 isa 指向的类是不是一个 KVO 类。如果不是,新建一个继承原来类的子类,并把 isa 指向这个新建的子类;
      检查对象的 KVO 类重写过没有这个 setter 方法。如果没有,添加重写的 setter 方法;
      添加这个观察者
     // 2. 检查对象 isa 指向的类是不是一个 KVO 类。如果不是,新建一个继承原来类的子类,并把 isa 指向这个新建的子类;
        
        Class clazz = object_getClass(self);
        NSString *className = NSStringFromClass(clazz);
        
        if (![className hasPrefix:kTYKVOClassPrefix]) {
            clazz = [self makeKvoClassWithOriginalClassName:className];
            // 设置isa指针
            object_setClass(self, clazz);
        }
    
    NSString *const kTYKVOClassPrefix = @"TYKVOClassPrefix_";
    
    #pragma mark 生成派生类
    - (Class)makeKvoClassWithOriginalClassName:(NSString *)originalClazzName
    {
        NSString *kvoClassName = [originalClazzName stringByAppendingString:kTYKVOClassPrefix];
        Class clazz = NSClassFromString(kvoClassName);
        
        if (!clazz) {
            return nil;
        }
        
        // 动态创建新的类需要用 objc/runtime.h 中定义的 objc_allocateClassPair() 函数。传一个父类,类名,然后额外的空间(通常为 0),它返回给你一个类。然后就给这个类添加方法,也可以添加变量。这里,我们只重写了 class 方法。哈哈,跟 Apple 一样,这时候我们也企图隐藏这个子类的存在。最后 objc_registerClassPair() 告诉 Runtime 这个类的存在。
        Class orignalClass = object_getClass(self);
        Class kvoClazz = objc_allocateClassPair(orignalClass, kvoClassName.UTF8String, 0);
        
        Method originalMethod = class_getInstanceMethod(orignalClass, @selector(class));
        const char *types = method_getTypeEncoding(originalMethod);
        class_addMethod(kvoClazz, @selector(class), (IMP)kvo_class, types);
        objc_registerClassPair(kvoClazz);
        
        return kvoClazz;
    }
    
    static Class kvo_class(id self, SEL _cmd)
    {
        return class_getSuperclass(object_getClass(self));
    }
    
    • 检查对象的 KVO 类是否重写过 setter 方法。如果没有,添加重写的 setter 方法;

    重写 setter 方法。新的 setter 在调用原 setter 方法后,通知每个观察者(调用之前传入的 block ):

    if (![self hasSelector:setterSelctor]) {
            const char *types = method_getTypeEncoding(setterMethod);
            class_addMethod(clazz, setterSelctor, (IMP)kvo_setter, types);
        }
    
    - (BOOL)hasSelector:(SEL)selector {
        Class clazz = object_getClass(self);
        unsigned int methodCount = 0;
        Method *methodList = class_copyMethodList(clazz, &methodCount);
        for (int i = 0; i < methodCount; i++) {
            Method method = methodList[i];
            SEL desSel = method_getName(method);
            if (desSel == selector) {
                free(methodList);
                return YES;
            }
        }
        free(methodList);
        return NO;
    }
    
    #pragma mark - Overridden Methods
    static void kvo_setter(id self, SEL _cmd, id newValue)
    {
        NSString *setterName = NSStringFromSelector(_cmd);
        NSString *getterName = getterForSetter(setterName);
        
        if (!getterName) {
            NSString *reason = [NSString stringWithFormat:@"Object %@ does not have setter %@", self, setterName];
            @throw [NSException exceptionWithName:NSInvalidArgumentException
                                           reason:reason
                                         userInfo:nil];
            return;
        }
        
        id oldValue = [self valueForKey:getterName];
        
        struct objc_super superclazz = {
            .receiver = self,
            .super_class = class_getSuperclass(object_getClass(self))
        };
        
        // cast our pointer so the compiler won't complain
        void (*objc_msgSendSuperCasted)(void *, SEL, id) = (void *)objc_msgSendSuper;
        
        // call super's setter, which is original class's setter method
        objc_msgSendSuperCasted(&superclazz, _cmd, newValue);
        
        // look up observers and call the blocks
        NSMutableArray *observers = objc_getAssociatedObject(self, (__bridge const void *)(kTYKVOAssociatedObservers));
        for (TYObservationInfo *each in observers) {
            if ([each.key isEqualToString:getterName]) {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    each.block(self, getterName, oldValue, newValue);
                });
            }
        }
    }
    
    • 最后一步,把这个观察的相关信息存在 associatedObject 里。观察的相关信息(观察者,被观察的 key, 和传入的 block )封装在 PGObservationInfo 类里。
    NSString *const kTYKVOAssociatedObservers = @"PGKVOAssociatedObservers";
    
    
    #pragma mark - TYObservationInfo
    @interface TYObservationInfo : NSObject
    
    @property (nonatomic, weak) NSObject *observer;
    @property (nonatomic, copy) NSString *key;
    @property (nonatomic, copy) TYObservingBlock block;
    
    @end
    
    @implementation TYObservationInfo
    
    - (instancetype)initWithObserver:(NSObject *)observer Key:(NSString *)key block:(TYObservingBlock)block
    {
        self = [super init];
        if (self) {
            _observer = observer;
            _key = key;
            _block = block;
        }
        return self;
    }
    
    
    // 4. 添加观察者等信息
        TYObservationInfo *info = [[TYObservationInfo alloc] initWithObserver:observer Key:key block:block];
        NSMutableArray *observers = objc_getAssociatedObject(self, (__bridge const void *)(kTYKVOAssociatedObservers));
        if (!observers) {
            observers = [NSMutableArray array];
            objc_setAssociatedObject(self, (__bridge const void *)(kTYKVOAssociatedObservers), observers, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }
        [observers addObject:info];
    
    // 移除观察者
    - (void)TY_removeObserver:(NSObject *)observer forKey:(NSString *)key {
        NSMutableArray* observers = objc_getAssociatedObject(self, (__bridge const void *)(kTYKVOAssociatedObservers));
        
        TYObservationInfo *infoToRemove;
        for (TYObservationInfo* info in observers) {
            if (info.observer == observer && [info.key isEqual:key]) {
                infoToRemove = info;
                break;
            }
        }
        
        [observers removeObject:infoToRemove];
    }
    

    完整代码

    NSObject+KVO.h
    //
    //  NSObject+KVO.h
    //  KVO--01
    //
    //  Created by Apple on 2018/6/14.
    //  Copyright © 2018年 com.tyler.edu. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    
    typedef void(^TYObservingBlock)(id observedObject, NSString *observedKey, id oldValue, id newValue);
    
    @interface NSObject (KVO)
    
    - (void)TY_addObserver:(NSObject *)observer
                    forKey:(NSString *)key
                 withBlock:(TYObservingBlock)block;
    
    - (void)TY_removeObserver:(NSObject *)observer forKey:(NSString *)key;
    
    @end
    
    
    NSObject+KVO.m
    //
    //  NSObject+KVO.m
    //  KVO--01
    //
    //  Created by Apple on 2018/6/14.
    //  Copyright © 2018年 com.tyler.edu. All rights reserved.
    //
    
    #import <objc/runtime.h>
    #import <objc/message.h>
    #import "NSObject+KVO.h"
    
    NSString *const kTYKVOClassPrefix = @"TYKVOClassPrefix_";
    
    NSString *const kTYKVOAssociatedObservers = @"PGKVOAssociatedObservers";
    
    
    #pragma mark - TYObservationInfo
    @interface TYObservationInfo : NSObject
    
    @property (nonatomic, weak) NSObject *observer;
    @property (nonatomic, copy) NSString *key;
    @property (nonatomic, copy) TYObservingBlock block;
    
    @end
    
    @implementation TYObservationInfo
    
    - (instancetype)initWithObserver:(NSObject *)observer Key:(NSString *)key block:(TYObservingBlock)block
    {
        self = [super init];
        if (self) {
            _observer = observer;
            _key = key;
            _block = block;
        }
        return self;
    }
    
    @end
    
    #pragma mark - Helpers
    static NSString * getterForSetter(NSString *setter)
    {
        if (setter.length <=0 || ![setter hasPrefix:@"set"] || ![setter hasSuffix:@":"]) {
            return nil;
        }
        
        // remove 'set' at the begining and ':' at the end
        NSRange range = NSMakeRange(3, setter.length - 4);
        NSString *key = [setter substringWithRange:range];
        
        // lower case the first letter
        NSString *firstLetter = [[key substringToIndex:1] lowercaseString];
        key = [key stringByReplacingCharactersInRange:NSMakeRange(0, 1)
                                           withString:firstLetter];
        
        return key;
    }
    
    static NSString * setterForGetter(NSString *getter) {
        {
            if (getter.length <= 0) {
                return nil;
            }
            
            // upper case the first letter
            NSString *firstLetter = [[getter substringToIndex:1] uppercaseString];
            NSString *remainingLetters = [getter substringFromIndex:1];
            
            // add 'set' at the begining and ':' at the end
            NSString *setter = [NSString stringWithFormat:@"set%@%@:", firstLetter, remainingLetters];
            
            return setter;
        }
    }
    
    #pragma mark - Overridden Methods
    static void kvo_setter(id self, SEL _cmd, id newValue)
    {
        NSString *setterName = NSStringFromSelector(_cmd);
        NSString *getterName = getterForSetter(setterName);
        
        if (!getterName) {
            NSString *reason = [NSString stringWithFormat:@"Object %@ does not have setter %@", self, setterName];
            @throw [NSException exceptionWithName:NSInvalidArgumentException
                                           reason:reason
                                         userInfo:nil];
            return;
        }
        
        id oldValue = [self valueForKey:getterName];
        
        struct objc_super superclazz = {
            .receiver = self,
            .super_class = class_getSuperclass(object_getClass(self))
        };
        
        // cast our pointer so the compiler won't complain
        void (*objc_msgSendSuperCasted)(void *, SEL, id) = (void *)objc_msgSendSuper;
        
        // call super's setter, which is original class's setter method
        objc_msgSendSuperCasted(&superclazz, _cmd, newValue);
        
        // look up observers and call the blocks
        NSMutableArray *observers = objc_getAssociatedObject(self, (__bridge const void *)(kTYKVOAssociatedObservers));
        for (TYObservationInfo *each in observers) {
            if ([each.key isEqualToString:getterName]) {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    each.block(self, getterName, oldValue, newValue);
                });
            }
        }
    }
    
    
    static Class kvo_class(id self, SEL _cmd)
    {
        return class_getSuperclass(object_getClass(self));
    }
    
    @implementation NSObject (KVO)
    
    - (void)TY_addObserver:(NSObject *)observer forKey:(NSString *)key withBlock:(TYObservingBlock)block {
        
        //1. 检查对象的类有没有相应的 setter 方法。如果没有抛出异常;
        SEL setterSelctor = NSSelectorFromString(setterForGetter(key));
        Method setterMethod = class_getInstanceMethod([self class], setterSelctor);
        
        if (!setterMethod) {
            // 抛出异常
            NSString *reason = [NSString stringWithFormat:@"Object %@ does not have a setter for key %@", self, key];
            NSException *exception = [NSException exceptionWithName:NSInvalidArgumentException reason:reason userInfo:nil];
            @throw exception;
            return;
        }
        
        // 2. 检查对象 isa 指向的类是不是一个 KVO 类。如果不是,新建一个继承原来类的子类,并把 isa 指向这个新建的子类;
        
        Class clazz = object_getClass(self);
        NSString *className = NSStringFromClass(clazz);
        
        if (![className hasPrefix:kTYKVOClassPrefix]) {
            clazz = [self makeKvoClassWithOriginalClassName:className];
            // 设置isa指针
            object_setClass(self, clazz);
        }
        
        // 3.检查对象的 KVO 类是否重写过 setter 方法。如果没有,添加重写的 setter 方法;
        if (![self hasSelector:setterSelctor]) {
            const char *types = method_getTypeEncoding(setterMethod);
            class_addMethod(clazz, setterSelctor, (IMP)kvo_setter, types);
        }
        
        // 4. 添加观察者等信息
        TYObservationInfo *info = [[TYObservationInfo alloc] initWithObserver:observer Key:key block:block];
        NSMutableArray *observers = objc_getAssociatedObject(self, (__bridge const void *)(kTYKVOAssociatedObservers));
        if (!observers) {
            observers = [NSMutableArray array];
            objc_setAssociatedObject(self, (__bridge const void *)(kTYKVOAssociatedObservers), observers, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }
        [observers addObject:info];
    }
    
    
    #pragma mark 生成派生类
    - (Class)makeKvoClassWithOriginalClassName:(NSString *)originalClazzName
    {
        NSString *kvoClassName = [originalClazzName stringByAppendingString:kTYKVOClassPrefix];
        Class clazz = NSClassFromString(kvoClassName);
        
        if (clazz) {
            return clazz;
        }
        
        // 动态创建新的类需要用 objc/runtime.h 中定义的 objc_allocateClassPair() 函数。传一个父类,类名,然后额外的空间(通常为 0),它返回给你一个类。然后就给这个类添加方法,也可以添加变量。这里,我们只重写了 class 方法。哈哈,跟 Apple 一样,这时候我们也企图隐藏这个子类的存在。最后 objc_registerClassPair() 告诉 Runtime 这个类的存在。
        Class orignalClass = object_getClass(self);
        Class kvoClazz = objc_allocateClassPair(orignalClass, kvoClassName.UTF8String, 0);
        
        Method originalMethod = class_getInstanceMethod(orignalClass, @selector(class));
        const char *types = method_getTypeEncoding(originalMethod);
        class_addMethod(kvoClazz, @selector(class), (IMP)kvo_class, types);
        objc_registerClassPair(kvoClazz);
        
        return kvoClazz;
    }
    
    // 移除观察者
    - (void)TY_removeObserver:(NSObject *)observer forKey:(NSString *)key {
        NSMutableArray* observers = objc_getAssociatedObject(self, (__bridge const void *)(kTYKVOAssociatedObservers));
        
        TYObservationInfo *infoToRemove;
        for (TYObservationInfo* info in observers) {
            if (info.observer == observer && [info.key isEqual:key]) {
                infoToRemove = info;
                break;
            }
        }
        
        [observers removeObject:infoToRemove];
    }
    
    - (BOOL)hasSelector:(SEL)selector {
        Class clazz = object_getClass(self);
        unsigned int methodCount = 0;
        Method *methodList = class_copyMethodList(clazz, &methodCount);
        for (int i = 0; i < methodCount; i++) {
            Method method = methodList[i];
            SEL desSel = method_getName(method);
            if (desSel == selector) {
                free(methodList);
                return YES;
            }
        }
        free(methodList);
        return NO;
    }
    
    @end
    
    
    使用

    新建立类 Fizz.h

    
    #import <Foundation/Foundation.h>
    
    @interface Fizz : NSObject
    
    @property (nonatomic, copy) NSNumber *number;
    
    @end
    
    

    新建立类 Fizz.m

    #import "Fizz.h"
    
    @implementation Fizz
    
    - (instancetype)init
    {
        self = [super init];
        if (self) {
            _number = @0;
        }
        return self;
    }
    
    @end
    

    在ViewConreoller.m 中测试

    #import "ViewController.h"
    #import "Fizz.h"
    #import "NSObject+KVO.h"
    
    @interface ViewController ()
    
    @property (nonatomic, strong) Fizz *f;
    
    @end
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.f = [[Fizz alloc] init];
        [self.f TY_addObserver:self forKey:@"number" withBlock:^(id observedObject, NSString *observedKey, id oldValue, id newValue) {
            NSLog(@"key = %@\n old = %@\n new = %@", observedKey, oldValue, newValue);
        }];
        self.f.number = @2;
    }
    

    参考如何自己动手实现 KVO

    相关文章

      网友评论

          本文标题:KVO

          本文链接:https://www.haomeiwen.com/subject/jmbeeftx.html