天天看點

iOS監聽模式之KVO、KVC的高階應用

KVC, KVO作為一種魔法貫穿日常Cocoa開發,筆者原先是準備寫一篇對其的全面總結,可網絡上對其的表面介紹已經夠多了,除去基本層面的使用,筆者跟大家談下平常在網絡上沒有提及的KVC, KVO進階知識。旨在分享交流。

目錄:

  • KVC的消息傳遞
  • KVC容器操作
  • KVC與容器類(集合代理對象)
  • KVO和容器類
  • KVO的實作原理

KVC的消息傳遞

valueForKey:的使用并不僅僅用來取值那麼簡單,還有很多特殊的用法,集合類也覆寫了這個方法,通過調用valueForKey:給容器中每一個對象發送操作消息,并且結果會被儲存在一個新的容器中傳回,這樣我們能很友善地利用一個容器對象建立另一個容器對象。另外,valueForKeyPath:還能實作多個消息的傳遞。一個例子:

NSArray *array = [NSArray arrayWithObject:@"10.11",
@"20.22", nil];
NSArray *resultArray = [array valueForKeyPath:@"doubleValue.intValue"];
NSLog(@"%@", resultArray);
//列印結果
(
    10,
    20
)      

KVC容器操作

容器不僅僅能使用KVC方法實作對容器成員傳遞普通的操作消息,KVC還定義了特殊的一些常用操作,使用valueForKeyPath:結合操作符來使用,所定義的keyPath格式入下圖所示 

iOS監聽模式之KVO、KVC的高階應用

Left key path:如果有,則代表需要操作的對象路徑(相對于調用者)

Collection operator:以"@"開頭的操作符

Right key path:指定被操作的屬性

正常操作符:

@avg、@count、@max、@min、@sum

對象操作符:

@distinctUnionOfObjects、@unionOfObjects

NSArray *values = [object valueForKeyPath:@"@unionOfObjects.value"];      

@distinctUnionOfObjects操作符傳回被操作對象指定屬性的集合并做去重操作,而@unionOfObjects則允許重複。如果其中任何涉及的對象為nil,則抛出異常。

Array和Set操作符:

Array和Set操作符操作對象是嵌套型的集合對象

  • @distinctUnionOfArrays、@unionOfArrays
NSArray *values = [arrayOfobjectsArrays valueForKeyPath:@"@distinctUnionOfArrays.value"];      

同樣的,傳回被操作集合下的集合中的對象的指定屬性的集合,并且做去重操作,而@unionOfObjects則允許重複。如果其中任何涉及的對象為nil,則抛出異常。

  • @distinctUnionOfSets
NSSet *values = [setOfobjectsSets valueForKeyPath:@"@distinctUnionOfSets.value"];      

傳回結果同理于NSArray。

據官方文檔說明,目前還不支援自動以操作符。

KVC與容器類(集合代理對象)

當然對象的屬性可以是一對一的,也可以是一對多。屬性的一對多關系其實就是一種對容器類的映射。如果有一個名為numbers的數組屬性,我們可以使用valueForKey:@"numbers"來擷取,這個是沒問題的,但KVC還能使用更靈活的方式管理集合。——集合代理對象

ElfinsArray.h
@interface ElfinsArray : NSObject
@property (assign ,nonatomic) NSUInteger count;
- (NSUInteger)countOfElfins;
- (id)objectInElfinsAtIndex:(NSUInteger)index;
@end
ElfinsArray.m
#import "ElfinsArray.h"
@implementation ElfinsArray
- (NSUInteger)countOfElfins {
    return  self.count;
}
- (id)objectInElfinsAtIndex:(NSUInteger)index {
    return [NSString stringWithFormat:@"小精靈%lu", (unsigned long)index];
}
@end
Main.m
- (void)work {
    ElfinsArray *elfinsArr = [ElfinsArray alloc] init];
    elfinsArr.count = 3;
    NSArray *elfins = [ElfinsArray valueForKey:@"elfins"];
    //elfins為KVC代理數組
    NSLog(@"%@", elfins);
    //列印結果
    (
        "小精靈0",
        "小精靈1",
        "小精靈2"
    )
}      

問題來了,ElfinsArray中并沒有定義elfins屬性,那麼elfins數組從何而來?valueForKey:有如下的搜尋規則:

  • 按順序搜尋getVal、val、isVal,第一個被找到的會用作傳回。
  • countOfVal,或者objectInValAtIndex:與valAtIndexes其中之一,這個組合會使KVC傳回一個代理數組。
  • countOfVal、enumeratorOfVal、memberOfVal。這個組合會使KVC傳回一個代理集合。
  • 名為val、isVal、val、isVal的執行個體變量。到這一步時,KVC會直接通路執行個體變量,而這種通路操作破壞了封裝性,我們應該盡量避免,這可以通過重寫+accessInstanceVariablesDirectly傳回NO來避免這種行為。

ok上例中我們實作了第二條中的特殊命名函數組合:

- (NSUInteger)countOfElfins;
- (id)objectInElfinsAtIndex:(NSUInteger)index;      

這使得我們調用valueForKey:@"elfins"時,KVC會為我們傳回一個可以響應NSArray所有方法的代理數組對象(NSKeyValueArray),這是NSArray的子類,- (NSUInteger)countOfElfins決定了這個代理數組的容量,- (id)objectInElfinsAtIndex:(NSUInteger)index決定了代理數組的内容。本例中使用的key是elfins,同理的如果key叫human,KVC就會去尋找-countOfHuman:

可變容器呢

當然我們也可以在可變集合(NSMutableArray、NSMutableSet、NSMutableOrderedSet)中使用集合代理:

這個例子我們不再使用KVC給我們生成代理數組,因為我們是通過KVC拿到的,而不能主動去操作它(insert/remove),我們聲明一個可變數組屬性elfins。

ElfinsArray.h
@interface ElfinsArray : NSObject
@property (strong ,nonatomic) NSMutableArray *elfins;
- (void)insertObject:(id)object inNumbersAtIndex:(NSUInteger)index;
- (void)removeObjectFromNumbersAtIndex:(NSUInteger)index;
@end
ElfinsArray.m
#import "ElfinsArray.h"
@implementation ElfinsArray
- (void)insertObject:(id)object inElfinsAtIndex:(NSUInteger)index {
[self.elfins insertObject:object atIndex:index];
NSLog(@"insert %@\n", object);
}
- (void)removeObjectFromElfinsAtIndex:(NSUInteger)index {
    [self.elfins removeObjectAtIndex:index];
    NSLog(@"remove\n");
}
@end
Main.m
- (void)work {
    ElfinsArray *elfinsArr = [ElfinsArray alloc] init];
    elfinsArr.elfins = [NSMutableArray array];
    NSMutableArray *delegateElfins = [ElfinsArray mutableArrayValueForKey:@"elfins"];
    //delegateElfins為KVC代理可變數組,非指向elfinsArr.elfins
    [delegateElfins insertObject:@"小精靈10" atIndex:0];
    NSLog(@"first log \n %@", elfinsArr.elfins);
    [delegateElfins removeObjectAtIndex:0];
    NSLog(@"second log \n %@", elfinsArr.elfins);
    //列印結果
    insert 小精靈10
    first log
    (
        "小精靈10"
    )
    remove
    second log
    (
    )
}      

上例中,我們通過調用

- mutableArrayValueForKey:
- mutableSetValueForKey:
- mutableOrderedSetValueForKey:      

KVC會給我們傳回一個代理可變容器delegateElfins,通過對代理可變容器的操作,KVC會自動調用合适KVC方法(如下):

//至少實作一個insert方法和一個remove方法

- insertObject:inValAtIndex:
- removeObjectFromValAtIndex:
- insertVal:atIndexes:
- removeValAtIndexes:      

間接地對被代理對象操作。

還有一組更強大的方法供參考

- replaceObjectInValAtIndex:withObject:
- replaceValAtIndexes:withVal:      

我認為這就是KVC結合KVO的結果。這裡我嘗試研究下了文檔中的如下兩個方法,還沒有什麼頭緒,知道的朋友可否告訴我下

- willChange:valuesAtIndexes:forKey:
- didChange:valuesAtIndexes:forKey:      

KVO和容器類

要注意,對容器類的觀察與對非容器類的觀察并不一樣,不可變容器的内容發生改變并不會影響他們所在的容器,可變容器的内容改變&内容增删也都不會影響所在的容器,那麼如果我們需要觀察某容器中的對象,首先我們得觀察容器内容的變化,在容器内容增加時添加對新内容的觀察,在内容移除同時移除對該内容的觀察。

既然容器内容數量改變和内容自身改變都不會觸發容器改變,此時對容器屬性施加KVO并沒有效果,那麼怎麼實作對容器變化(非容器改變)的觀察呢?上面所介紹的代理容器能幫到我們:

//我們通過KVC拿到容器屬性的代理對象
NSMutableArray *delegateElfins = [ElfinsArray mutableArrayValueForKey:@"elfins"];
[delegateElfins addObject:@"小精靈10"];      

當然這樣做的前提是要實作insertObject:inValAtIndex:和removeObjectFromValAtIndex:兩個方法。如此才能觸發observeValueForKeyPath:ofObject:change:context:的響應。

而後,我們就可以輕而易舉地在那兩個方法實作内對容器新成員添加觀察/對容器廢棄成員移除觀察。

KVO的實作原理

寫到這裡有點犯困,估計廣州的春天真的來了。對于KVO的實作原理就不花筆墨再描述了,網絡上哪裡都能找到,這裡借網上一張圖來偷懶帶過。

iOS監聽模式之KVO、KVC的高階應用

在我們了解明白實作原理的前提下,我們可以自己來嘗試模仿,那麼我們從哪裡下手呢?先來準備一個新子類的setter方法:

- (void)notifySetter:(id)newValue {
    NSLog(@"我是新的setter");
}      

setter的實作先留白,下面再詳細說,緊接着,我們直接進入主題,runtime注冊一個新類,并且讓被監聽類的isa指針指向我們自己僞造的類,為了大家看得友善,筆者就不做封裝了,所有直接寫在一個方法内:

- (Class)configureKVOSubClassWithSourceClassName:(NSString *)className observeProperty:(NSString *)property {
    NSString *prefix = @"NSKVONotifying_";
    NSString *subClassName = [prefix stringByAppendingString:className];
    //1
    Class originClass = [KVOTargetClass class];
    Class dynaClass = objc_allocateClassPair(originClass, subClassName.UTF8String, 0);
    //重寫property對應setter
    NSString *propertySetterString = [@"set" stringByAppendingString:[[property substringToIndex:1] uppercaseString]];
    propertySetterString = [propertySetterString stringByAppendingString:[property substringFromIndex:1]];
    propertySetterString = [propertySetterString stringByAppendingString:@":"];
    SEL setterSEL = NSSelectorFromString(propertySetterString);
    //2
    Method setterMethod = class_getInstanceMethod(originClass, setterSEL);
    const char types = method_getTypeEncoding(setterMethod);
    class_addMethod(dynaClass, setterSEL, class_getMethodImplementation([self class], @selector(notifySetter:)), types);
    objc_registerClassPair(dynaClass);
    return dynaClass;
}      

我們來看

//1處,我們要建立一個新的類,可以通過objc_allocateClassPair來建立這個新類和他的元類,第一個參數需提供superClass的類對象,第二個參數接受新類的類名,類型為const char *,通過傳回值我們得到dynaClass類對象。

//2處,我們希望為我們的僞造的類添加跟被觀察類一樣隻能的setter方法,我們可以借助被觀察類,拿到類型編碼資訊,通過class_addMethod,注入我們自己的setter方法實作:class_getMethodImplementation([self class], @selector(notifySetter:)),最後通過objc_registerClassPair完成新類的注冊!。

可能有朋友會問class_getMethodImplementation中擷取IMP的來源[self class]的self是指代什麼?其實就是指代我們自己的setter(notifySetter:)IMP實作所在的類,指代從哪個類可以找到這個IMP,筆者這裡是直接開一個新工程,在ViewController裡就開幹的,notifySetter:和這個手術方法configureKVOSubClassWithSourceClassName: observeProperty:所在的地方就是VC,是以self指向的就是這個VC執行個體,也就是這個手術方法的調用者。

不用懷疑,經過手術後對KVOTargetClass對應屬性的修改,就會進入到我們僞裝的setter,下面我們來完成先前留白的setter實作:

- (void)notifySetter:(id)newValue {
    NSLog(@"我是新的setter");
    struct objc_super originClass = {
        .receiver = self,
        .super_class = class_getSuperclass(object_getClass(self))
    };
    NSString *setterName = NSStringFromSelector(_cmd);
    NSString *propertyName = [setterName substringFromIndex:3];
    propertyName = [[propertyName substringToIndex:propertyName.length - 1] lowercaseString];
    [self willChangeValueForKey:propertyName];
    //調用super的setter
    //1
    void (*objc_msgSendSuperKVO)(void * class, SEL _cmd, id value) = (void *)objc_msgSendSuper;
    //2
    objc_msgSendSuperKVO(&originClass, _cmd, newValue);
    [self didChangeValueForKey:propertyName];
}      

我們輕而易舉地讓willChangeValueForKey:和didChangeValueForKey:包裹了對newValue的修改。

這裡需要提的是:

//1處,在IOS8後,我們不能直接使用objc_msgSend()或者objc_msgSendSuper()來發送消息,我們必須自定義一個msg_Send函數并提供具體類型來使用。

//2處,至于objc_msgSendSuper(struct objc_super *, SEL, ...),第一個參數我們需要提供一個objc_super結構體,我們command跳進去來看看這個結構體:

/// Specifies the superclass of an instance.
struct objc_super {
    /// Specifies an instance of a class.
    __unsafe_unretained id receiver;
    /// Specifies the particular superclass of the instance to message.
    #if !defined(__cplusplus)  &&  !__OBJC2__
    /* For compatibility with old objc-runtime.h header */
    __unsafe_unretained Class class;
    #else
    __unsafe_unretained Class super_class;
    #endif
    /* super_class is the first class to search */
};
#endif      

第一個成員receiver表示某個類的執行個體,第二個成員super_class代表目前類的父類,也就是這裡接受消息目标的類。

工作已經完成了,可以随便玩了:

- (void)main {
    KVOTargetClass *kvoObject = [[KVOTargetClass alloc] init];
    NSString *targetClassName = NSStringFromClass([KVOTargetClass class]);
    Class subClass = [self configureKVOSubClassWithSourceClassName:targetClassName observeProperty:@"name"];
    object_setClass(kvoObject, subClass);
    [kvoObject setName:@"haha"];
    NSLog(@"property -- %@", kvoObject.name);
}      

KVO驗證筆者就懶得驗了,有興趣的朋友可以試試。最後,感謝!

參考文獻

objc.io

NSKeyValueObserving Protocol Reference

Apple developer

繼續閱讀