無論採用 MVC 還是 MVVM 架構,我們都需要「model 的改變能及時同步到相關元件」。這類似觀察者模式,在 iOS 中可以用 KVO 完成,但每次都手寫 KVO 會讓程式碼變得雜亂。這裡可以借助 GitHub 上的 THBinder,並在其基礎上稍作加工,讓我們僅用一個宏就能完成綁定,而不必自己保存 THBinder 實例。
首先是支援綁定的基礎設施,透過關聯物件把每個 binder 掛到被觀察的實例上,並在 dealloc 時自動解除綁定:
#import "THBinder.h" #import "THObserver.h" #import#import #define TMBindDictoryKey "__TMBindDictoryKey" #define BindKey(target, keyPath) [NSString stringWithFormat:@"__binder__%@", keyPath] static NSMutableSet *swizzledClasses() { static dispatch_once_t onceToken; static NSMutableSet *swizzledClasses = nil; dispatch_once(&onceToken, ^{ swizzledClasses = [[NSMutableSet alloc] init]; }); return swizzledClasses; } static void swizzleDeallocIfNeeded(Class classToSwizzle) { @synchronized (swizzledClasses()) { NSString *className = NSStringFromClass(classToSwizzle); if ([swizzledClasses() containsObject:className]) return; SEL deallocSelector = sel_registerName("dealloc"); SEL swizzleDeallocSelector = sel_registerName("swizzleDelloc"); __block void (*originalDealloc)(__unsafe_unretained id, SEL) = NULL; id newDealloc = ^(__unsafe_unretained id self) { if (class_respondsToSelector(classToSwizzle, swizzleDeallocSelector)) objc_msgSend(self, swizzleDeallocSelector); if (originalDealloc == NULL) { struct objc_super superInfo = { .receiver = self, .super_class = class_getSuperclass(classToSwizzle) }; objc_msgSendSuper(&superInfo, deallocSelector); } else { originalDealloc(self, deallocSelector); } }; IMP newDeallocIMP = imp_implementationWithBlock(newDealloc); if (!class_addMethod(classToSwizzle, deallocSelector, newDeallocIMP, "v@:")) { Method deallocMethod = class_getInstanceMethod(classToSwizzle, deallocSelector); originalDealloc = (__typeof__(originalDealloc))method_getImplementation(deallocMethod); originalDealloc = (__typeof__(originalDealloc))method_setImplementation(deallocMethod, newDeallocIMP); } [swizzledClasses() addObject:className]; } } @interface NSObject (SupportBinding) - (void)setBinder:(id)binder keyPath:(NSString*)keyPath; @end @implementation NSObject (SupportBinding) - (void)swizzleDelloc { NSMutableDictionary *bindDict = objc_getAssociatedObject(self, TMBindDictoryKey); [bindDict enumerateKeysAndObjectsUsingBlock:^(id key, NSArray *obj, BOOL *stop) { [obj enumerateObjectsUsingBlock:^(THBinder *binder, NSUInteger idx, BOOL *stop) { [binder stopBinding]; }]; }]; objc_setAssociatedObject(self, TMBindDictoryKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (void)setBinder:(id)binder keyPath:(NSString*)keyPath { NSMutableDictionary *bindDict = objc_getAssociatedObject(self, TMBindDictoryKey); if (!bindDict) { bindDict = [NSMutableDictionary new]; objc_setAssociatedObject(self, TMBindDictoryKey, bindDict, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } NSString *keyName = BindKey(self, keyPath); id object = [bindDict valueForKey:keyName]; if ([object containsObject:binder]) return; if (!object) object = [NSMutableArray new]; [object addObject:binder]; [bindDict setValue:object forKey:keyName]; swizzleDeallocIfNeeded(self.class); } @end
接著在 THBinder 中加入一個方法,讓它在建立時把 binder 保存到被觀察的實例裡:
- (id)initForBindingFromObject:(id)fromObject keyPath:(NSString *)fromKeyPath
toObject:(id)toObject keyPath:(NSString *)toKeyPath
transformationBlock:(THBinderTransformationBlock)transformationBlock {
if ((self = [super init])) {
__weak id wToObject = toObject;
NSString *myToKeyPath = [toKeyPath copy];
THObserverBlockWithChangeDictionary changeBlock;
if (transformationBlock) {
changeBlock = [^(NSDictionary *change) {
[wToObject setValue:transformationBlock(change[NSKeyValueChangeNewKey]) forKeyPath:myToKeyPath];
} copy];
} else {
changeBlock = [^(NSDictionary *change) {
[wToObject setValue:change[NSKeyValueChangeNewKey] forKeyPath:myToKeyPath];
} copy];
}
_observer = [THObserver observerForObject:fromObject keyPath:fromKeyPath
options:NSKeyValueObservingOptionNew
changeBlock:changeBlock];
[fromObject setBinder:self keyPath:fromKeyPath];
}
return self;
}最後,借用 ReactiveCocoa 的 keypath 宏來組織 TMBIND 宏,使用時一行搞定,binder 會自動被掛到被觀察的實例上:
#ifndef KVODemo_Binder_h
#define KVODemo_Binder_h
#import "EXTKeyPathCoding.h"
#import "THObserver.h"
#import "THBinder.h"
// 單向綁定
#define TMBIND(_fromObject_, _fromKeyPath_, _toObject_, _toKeyPath_) \
[THBinder binderFromObject:_fromObject_ \
keyPath:@keypath(_fromObject_, _fromKeyPath_) \
toObject:_toObject_ \
keyPath:@keypath(_toObject_, _toKeyPath_)]
#define TMBIND_WITH_TRANSFORMBLOCK(_fromObject_, _fromKeyPath_, _toObject_, _toKeyPath_, _transfromBlock_) \
[THBinder binderFromObject:_fromObject_ \
keyPath:@keypath(_fromObject_, _fromKeyPath_) \
toObject:_toObject_ \
keyPath:@keypath(_toObject_, _toKeyPath_) \
transformationBlock:_transfromBlock_];
#endif如此一來,只要一個 TMBIND 宏,就能完成屬性間的即時同步,binder 的生命周期也由被觀察物件自動管理,不必再手動保存。