KVO

2018-06-14  本文已影响0人  foolish_hungry

优雅地使用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 不是永远都生效的。而且这不是一个好的设计。

原来,这个中间类,继承自原本的那个类。不仅如此,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:
//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)。如果没有,自然要抛出异常。

 // 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));
}

重写 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);
            });
        }
    }
}
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

上一篇下一篇

猜你喜欢

热点阅读