IOS底层 - 如何自定义KVO

一、思路概览

以前写了一篇kvo原理探索,今天咱们来本身动手实现它的逻辑,这样咱们对kvo的认识会更深入一些。git

咱们根据系统kvo的使用,咱们须要定义如下接口:github

- 添加观察者
  - 接收通知回调
  - 移除观察者
复制代码

可是为了更加完善一些,咱们又添加了automatically方法、ss_willChangeValueForKey:ss_didChangeValueForKey:等方法,真正实现手自一体web

二、接口定义

根据系统KVO的相关接口,咱们也给NSObject添加一个Category,具体的头文件咱们定义以下:编辑器

typedef NS_OPTIONS(NSUInteger, SSKeyValueObservingOptions) {
    SSKeyValueObservingOptionNew = 0x01,
    SSKeyValueObservingOptionOld = 0x02,
};

@interface NSObject (SSKVO)

 /** Register an observer of the value at a key path relative to the receiver */
- (void)ss_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(SSKeyValueObservingOptions)options context:(nullable  void *)context;

/* deregister as an observer of the value at a key path relative to the receiver*/
- (void)ss_removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(nullable  void *)context;

/* Given that the receiver has been registered as an observer of the value at a key path relative to an object, be notified of a change to that value */
- (void)ss_observeValueForKeyPath:(nullable  NSString *)keyPath ofObject:(nullable  id)object change:(nullable  NSDictionary<NSKeyValueChangeKey, id> *)change context:(nullable  void *)context;

+ (BOOL)ss_automaticallyNotifiesObserversForKey:(NSString *)key;

- (void)ss_willChangeValueForKey:(NSString *)key;

- (void)ss_didChangeValueForKey:(NSString *)key;

@end
复制代码

二、接口实现

接口定义完了以后,咱们就针对定义的接口方法,一一去实现逻辑:post

2.1 观察者包装

因为咱们须要保存观察者的相关信息以便于在后续的设值和传值更加方便,此处咱们封装一个SSKVOInfo的对象,考虑到一个对象有多个属性值可能会被观察,咱们建立一个以keyPath做为键值的一个字典,保存了多有keyPath的观察者信息。测试

@interface SSKVOInfo : NSObject {
    @public
     id observer;
    void *context;
    int options;
    NSString *keyPath;
    NSDictionary *changes;
}
@end
 @implementation SSKVOInfo
 @end
复制代码

那么接下来咱们一一针对咱们的接口去实现:ui

2.2 添加观察者

- (void)ss_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(SSKeyValueObservingOptions)options context:(nullable  void *)context {
    // 动态生成子类
    Class replacement = [self replacementClass];
    // 添加setter方法
    {
        SEL sel = NSSelectorFromString(setterForGetter(keyPath));
        Method method = class_getInstanceMethod(self.class, sel);
        const  char *types = method_getTypeEncoding(method);
        /** 重写setter方法 */
        class_addMethod(replacement , sel, (IMP)ss_setter, types);
    }
    SSKVOInfo *kvoInfo = [SSKVOInfo new];
    kvoInfo->context = context;
    kvoInfo->options = options;
    kvoInfo->keyPath = keyPath;
    kvoInfo->observer = observer;
    kvoInfo->changes = @{};
    // 添加信息
    [self addKVOInfo:kvoInfo forKey:keyPath];
}
复制代码

SSKVOInfo相关方法以下:spa

- (SSKVOInfo *)kvoInfoForKey:(NSString *)key {
    NSMutableDictionary *observerInfo = objc_getAssociatedObject(self, (__bridge const  void * _Nonnull)(SSKVOAssiociateKey));
    id object = [observerInfo objectForKey:key];
    if (object && [object isKindOfClass:[SSKVOInfo class]]) {
        return object;
    }
    return  nil;
}
- (void)addKVOInfo:(SSKVOInfo *)kvoInfo forKey:(NSString *)key {
    NSMutableDictionary *observerInfo = objc_getAssociatedObject(self, (__bridge const  void * _Nonnull)(SSKVOAssiociateKey));
    if (!observerInfo) {
        observerInfo = [NSMutableDictionary dictionary];
    }
    [observerInfo setObject:kvoInfo forKey:key];
    objc_setAssociatedObject(self, (__bridge const  void * _Nonnull)(SSKVOAssiociateKey), observerInfo, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
复制代码

2.3 通知回调

何时发送通知呢???调试

/** 重写set方法 */
 void ss_setter(id self, SEL _cmd, id value)
{
    NSString *v = NSStringFromSelector(_cmd);
    NSString *key = getterForSetter(v);
    Class c = [self  class];
    /** 自动观察,咱们自动调用ss_willChangeValueForKey 和 ss_didChangeValueForKey*/
     if ([c ss_automaticallyNotifiesObserversForKey:key]) {
        [self ss_willChangeValueForKey:key];
        /** 调用父类的set方法 */
        ss_sendSuper(self, _cmd, value);
        [self ss_didChangeValueForKey:key];
    } else {// 只调用父类方法,若是父类本身实现will和did方法,也会发送通知
        ss_sendSuper(self, _cmd, value);
    }
}
复制代码

其关联的手动KVO实现以下:code

/** 调用父类的set方法 */
 void ss_sendSuper(id self, SEL _cmd, id value)
{
    void (*ss_msgSendSuper)(void *,SEL , id) = (void *)objc_msgSendSuper;
    // void /* struct objc_super *super, SEL op, ... */
     struct objc_super superStruct = {
        .receiver = self,
        .super_class = class_getSuperclass(object_getClass(self)),
    };
    //objc_msgSendSuper(&superStruct,_cmd,newValue)
    ss_msgSendSuper(&superStruct,_cmd,value);
}
- (void)ss_willChangeValueForKey:(NSString *)key {
    [self saveCurrentValueFor:SSKVO_Old keyPath:key];
}
- (void)ss_didChangeValueForKey:(NSString *)key {
    [self saveCurrentValueFor:SSKVO_New keyPath:key];
    [self sendNotification:key];
} 
- (void)saveCurrentValueFor:(NSString *)changeKey  keyPath:(NSString *)keyPath {
    id object = [self kvoInfoForKey:keyPath];
    if (!object || ![object isKindOfClass:[SSKVOInfo class]]) {return;}
    SSKVOInfo *kvoInfo = (SSKVOInfo *)object;
    NSMutableDictionary *changes = kvoInfo->changes.mutableCopy;
    id value = [self valueForKey:keyPath]?[self valueForKey:keyPath]:@"";
    [changes setObject:value forKey:changeKey];
    kvoInfo->changes = changes.copy;
}
- (void)sendNotification:(NSString *)keyPath {
    id object = [self kvoInfoForKey:keyPath];
    if (!object || ![object isKindOfClass:[SSKVOInfo class]]) {return;}
    SSKVOInfo *kvoInfo = (SSKVOInfo *)object;
    // send notification
     id observer = kvoInfo->observer;
    // 发送通知
     if (observer && [observer respondsToSelector:@selector(ss_observeValueForKeyPath:ofObject:change:context:)]) {
        int options = kvoInfo->options;
        NSDictionary *changes = kvoInfo->changes;
        NSMutableDictionary *info = [NSMutableDictionary dictionaryWithCapacity:2];
        if (options & SSKeyValueObservingOptionNew) {
            [info setObject:changes[SSKVO_New] forKey:SSKVO_New];
        }
        if (options & SSKeyValueObservingOptionOld) {
            [info setObject:changes[SSKVO_Old] forKey:SSKVO_Old];
        }
        [observer ss_observeValueForKeyPath:keyPath ofObject:self change:info context:kvoInfo->context];
    }
}
复制代码

2.4 移除观察者

- (void)ss_removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(nullable  void *)context {
    [self removeKVOInfoForKey:keyPath];
}
- (void)removeKVOInfoForKey:(NSString *)key {
    NSMutableDictionary *observerInfo = objc_getAssociatedObject(self, (__bridge const  void * _Nonnull)(SSKVOAssiociateKey));
    [observerInfo removeObjectForKey:key];
    objc_setAssociatedObject(self, (__bridge const  void * _Nonnull)(SSKVOAssiociateKey), observerInfo, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (observerInfo.count<=0) {
        // 指回给父类
        Class superClass = [self class];
        object_setClass(self, superClass);
    }
}
复制代码

三、调试

代码逻辑实现了,必不可少的就是测试了:

这是自动挡,接下来咱们试试手动挡如何,调整SSPerson的实现以下:

#import "SSPerson.h"
 #import "NSObject+SSKVO.h"

 @implementation SSPerson

+ (BOOL)ss_automaticallyNotifiesObserversForKey:(NSString *)key {
    return  NO;
}

- (void)setName:(NSString *)name {
    [self ss_willChangeValueForKey:NSStringFromSelector(@selector(name))];
    _name = @"here is custom value";
    [self ss_didChangeValueForKey:NSStringFromSelector(@selector(name))];
}

@end
复制代码

运行一样点击两次屏幕咱们看看打印结果是否为here is custom value

四、总结

至此咱们大概完成了自定义kvo的实现,上述只展现了一些主要的核心逻辑,具体的代码须要的话请前往SSKVO-demo下载,若是说这份代码不够缜密,那是固然的,好比咱们只处理了对象类型的属性观察缺乏了基本类型的处理,好比咱们的keyPath只是针对key并无path的处理,还有针对KVC是如何触发KVO的实现等等,这些后续我都会去完善,也但愿您能多多赐教和点评。最后,看完别忘了...

相关文章
相关标签/搜索