mac開發系列30:ServiceCenter和ExtensionCenter源碼理解

單例和delegate是oc最常用的兩種設計模式。其實從設計模式層面而言,delegate叫做觀察者模式更為貼切。ServiceCenter和ExtensionCenter分別為了集中管理單例和delegate。
一、ServiceCenter
微信中不少對象都是要面向全局提供service的,如:賬號相關的AccountService、CDN相關的CdnComMgr、delegate管理相關的ExtensionCenter等等,頻繁地創建和銷毀這些對象顯然是不科學的,因此要實現成單例。但若就此滿足,這些單例創建方式不一,且散落在代碼各處,降低了代碼可讀性,還不利于銷毀并回收資源。于是,參考簡單工廠模式的思想(新增一個工廠類來負責其他類的對象創建),即ServiceCenter,統一的創建接口如下:

define GET_SERVICE(obj) ((obj*)[[MMServiceCenter defaultCenter] getService:[obj class]])

上述GET_SERVICE宏中,getService方法實現及相關comment如下:
@interface MMServiceCenter : NSObject{ NSMutableDictionary *m_dicService; //存儲單例的字典。key:單例所屬的類,value:單例 NSRecursiveLock *m_lock;}@end

-(id) getService:(Class) cls{ [m_lock lock]; // 上鎖,防止同時寫m_dicService id obj = [m_dicService objectForKey:cls]; //查找單例 if (obj == nil) //單例還沒創建 { // 單例所屬的類必須繼承MMService類,并遵循MMService協議 // 因為MMService類和協議聲明了,管理單例的方法和變量,如: // 微信在前臺時,這些單例怎么處理;微信進入后臺,它們又是什么狀態; // 微信退出后,單例是否還需要駐留內存等等 if (![cls isSubclassOfClass:[MMService class]]) { [m_lock unlock]; return nil; } if (![cls conformsToProtocol:@protocol(MMService)]) { [m_lock unlock]; return nil; } // 創建單例并添加到字典中 obj = [[cls alloc] init]; [m_dicService safeSetObject:obj forKey:cls]; [m_lock unlock]; // 如果單例實現了MMService協議中的可選方法onServiceInit,則 // 可以用這個方法來做一些額外的初始化工作 if ([obj respondsToSelector:@selector(onServiceInit)]) { [obj onServiceInit]; } } else { [m_lock unlock]; } return obj;}

@interface MMService : NSObject // 單例通過設置這個屬性來決定自己在微信退出后,是否繼續駐留內存@property (assign) BOOL m_isServicePersistent;@end@protocol MMService<NSObject>@optional-(void) onServiceInit; // 單例創建后,做些額外的初始化工作-(void) onServiceClearData; // 微信退出登錄,回收資源。(其實真正刪除單例的是removeService,只不過這兩個方法常常一起被調用)// 如果m_isServicePersistent=YES,就不會調用removeService了@end

基本類圖結構如下:



下面以AccountService為例,闡述整體流程:
1、定義AccountService類,繼承MMService類,并遵循MMService協議:



2、從ServiceCenter獲取AccountService單例,并調用所需方法:

3、微信退出登錄,協議方法被調用來回收資源:



補充真正刪除單例,徹底回收資源的removeService方法:
-(void) removeService:(Class) cls{ [m_lock lock]; MMService<MMService>* obj = [m_dicService objectForKey:cls]; if (obj == nil) { [m_lock unlock]; return ; } [m_dicService safeRemoveObjectForKey:cls]; // 從字典中刪除,單例的引用計數變為0,觸發ARC調用單例的dealloc方法 [m_lock unlock];}

二、ExtensionCenter
我們知道,delegate是通過protocol來實現的:雙方遵循同一個協議,一方實現協議中的方法(即觀察者),另一方調用協議中的方法。原理圖如下:



ExtensionCenter就是把這種delegate關系統一登記維護、集中管理,并提供自己的調用方式。至于為啥叫ExtensionCenter就不知道了,這個Extension(ext)跟類擴展沒有半毛錢關系,可以看做Protocol加強版。下面闡述整體實現流程及其原理:
1、登記,其實就是把“觀察者(obj)遵循協議(ext),并實現協議中的方法”這種關系用數據結構維護起來。這樣,后續廣播事件通知(即調用協議方法),就可以找到對應的觀察者:
REGISTER_EXTENSION(IMessageExt, self);

define REGISTER_EXTENSION(ext, obj) \ { \ MMExtension *oExt = [GET_SERVICE(MMExtensionCenter) getExtension:@protocol(ext)]; \ if (oExt) { \ [oExt registerExtension:obj]; \ } \ }

   從REGISTER_EXTENSION宏可以看到,ExtensionCenter就是ServiceCenter管理的一個單例。主要存儲數據結構,以及宏實現里的兩個方法解析:

1)主要存儲數據結構:
// 方法描述struct objc_method_description { SEL name; // 方法名,即selector char *types; // 方法參數類型數組};

typedef Protocol *MMExtKey;@interface MMExtension : NSObject { MMExtKey m_extKey; // 協議 unsigned int m_methodCount; // 協議中方法個數 struct objc_method_description *m_methods; // 協議方法數組 // key:協議方法名,value:MMExtensionObject(協議方法的實現者,即觀察者)數組 MMExtensionDictionary *m_dicObserver;}@end@interface MMExtensionCenter : MMService <MMService> { // key:協議名,value:MMExtension NSMutableDictionary *m_dicExtension;}@end

// REGISTER_EXTENSION后,觀察者會被引用;而觀察者dealloc時才會調用UNREGISTER_EXTENSION,// 但是因為被引用了,觀察者的dealloc不會被調到,也就沒法調到UNREGISTER_EXTENSION,即造成相互// 引用。為了解決相互引用,使用如下觀察者封裝類MMExtensionObject@interface MMExtensionObject : NSObject { __unsafe_unretained id m_Obj; // 弱引用,不增加引用計數。這種套路在MMTimer中也有用到 BOOL m_deleteMark; // 標記刪除,即取消登記}@property (nonatomic, assign) BOOL m_deleteMark;- (void)setObject:(id)Obj;- (id)getObject;- (BOOL)isObjectEqual:(id)Obj;@end

數據結構關系圖如下:



2)getExtension:

  • (MMExtension *)getExtension:(MMExtKey)oKey { NSString *key = NSStringFromProtocol(oKey); // 獲取協議名 MMExtension *ext = [m_dicExtension objectForKey:key]; // 查找協議名對應的MMExtension if (ext == nil) { // MMExtension還沒創建 // 創建協議對應的MMExtension,并添加到字典中 ext = [[MMExtension alloc] initWithKey:oKey]; [m_dicExtension safeSetObject:ext forKey:key]; } return ext;}

3)registerExtension:

  • (BOOL)registerExtension:(id)oObserver {// 觀察者沒有遵循協議,不能登記 if ([oObserver conformsToProtocol:m_extKey] == NO) { return NO; } if (m_dicObserver == nil) { m_dicObserver = [[MMExtensionDictionary alloc] init]; } Class cls = [oObserver class];// 遍歷協議中的所有方法 for (unsigned int index = 0; index < m_methodCount; index++) { objc_method_description *method = &m_methods[index]; // 觀察者實現了協議方法,就登記 if (class_respondsToSelector(cls, method->name)) { [m_dicObserver registerExtension:oObserver forKey:NSStringFromSelector(method->name)]; } } return YES;}

登記“觀察者實現了某個協議方法”:

  • (BOOL)registerExtension:(id)oObserver forKey:(id)nsKey { if (oObserver == nil || nsKey == nil) { return NO; }// 獲取一個協議方法的實現者數組
    NSMutableArray *selectorImplememters = [m_dic objectForKey:nsKey];// 該協議方法還沒有實現者,就創建一個空的實現者數組,并添加到字典中 if (selectorImplememters == nil) { selectorImplememters = [[NSMutableArray alloc] init]; [m_dic safeSetObject:selectorImplememters forKey:nsKey]; }// 要登記的觀察者,已經登記過了,直接返回NO for (MMExtensionObject *extObj in selectorImplememters) { if ([extObj isObjectEqual:oObserver]) { return NO; } }// 沒登記過,就登記 MMExtensionObject *extObj = [[MMExtensionObject alloc] initWithObject:oObserver]; [selectorImplememters safeAddObject:extObj]; return YES;}

2、向觀察者廣播事件通知,即調用一個協議方法,所有實現了該協議方法的觀察者都會收到通知,其核心就是查找一個協議方法的所有觀察者,然后調用它實現的協議方法(只要理解了上面的數據結構關系圖,就很簡單了):
SAFECALL_EXTENSION(IMessageExt, @selector(onAddMsg:msgData:), onAddMsg : nsChatName msgData : msgData);

define SAFECALL_EXTENSION(ext, sel, func) \ {// 對于LAZY_REGISTER_EXTENSION,只是登記了類名;SAFECALL_EXTENSION時, // 要根據類名,通過ServiceCenter,創建對應的觀察者obj單例 \ [GET_SERVICE(LazyExtensionAgent) ensureLazyListenerInitedForExtension:@protocol(ext) withSelector:sel]; \ MMExtension *oExt = [GET_SERVICE(MMExtensionCenter) getExtension:@protocol(ext)]; \ if (oExt) { \ NSArray *ary = [oExt getExtensionListForSelector:sel]; \ for (UInt32 index = 0; index < ary.count; index++) { \ MMExtensionObject *obj = [ary objectAtIndex:index]; \ if (obj.m_deleteMark == YES) continue; \ id oExtObj = [obj getObject]; \ { [oExtObj func]; } \ } \ } \ }

下面給出LAZY_REGISTER_EXTENSION的解析:

define LAZY_REGISTER_EXTENSION(ext, cls) \ { [GET_SERVICE(LazyExtensionAgent) registerLazyListener:[cls class] onExtension:@protocol(ext)]; }

  • (void)registerLazyListener:(Class)cls onExtension:(MMExtKey)extKey { if (cls == NULL || extKey == nil) { return; } if (![cls conformsToProtocol:extKey]) { return; } // 根據協議名查找協議的監聽者(其實就是實現者、觀察者) NSString *nsExtKey = NSStringFromProtocol(extKey); NSMutableDictionary *dicListeners = [m_dicExtensions objectForKey:nsExtKey]; if (dicListeners == nil) {// 該協議還沒有監聽者,就創建一個監聽者空數組,添加到字典中 dicListeners = [[NSMutableDictionary alloc] init]; [m_dicExtensions safeSetObject:dicListeners forKey:nsExtKey]; } // 可選協議方法登記 unsigned int count = 0; objc_method_description *optionalMethods = protocol_copyMethodDescriptionList(extKey, NO, YES, &count); if (optionalMethods && count > 0) { [self addListener:cls toDic:dicListeners forMethods:optionalMethods methodCount:count]; free(optionalMethods); } // 必選協議方法登記 count = 0; objc_method_description *requiredMethods = protocol_copyMethodDescriptionList(extKey, YES, YES, &count); if (requiredMethods && count > 0) { [self addListener:cls toDic:dicListeners forMethods:requiredMethods methodCount:count]; free(requiredMethods); }}

  • (void)addListener:(Class)cls toDic:(NSMutableDictionary *)dicListeners forMethods:(objc_method_description *)arrMethods methodCount:(unsigned int)count { for (unsigned int index = 0; index < count; index++) { objc_method_description method = arrMethods[index]; if (class_respondsToSelector(cls, method.name)) { NSString *nsSelector = NSStringFromSelector(method.name); NSMutableSet *selectorImplememters = [dicListeners objectForKey:nsSelector]; if (selectorImplememters == nil) { selectorImplememters = [[NSMutableSet alloc] init]; [dicListeners safeSetObject:selectorImplememters forKey:nsSelector]; }// 以類名(而非obj)作為實現者來登記 [selectorImplememters safeAddObject:NSStringFromClass(cls)]; } }}

根據LAZY_REGISTER_EXTENSION登記的類名,通過ServiceCenter創建類名對應的單例obj:

  • (void)ensureLazyListenerInitedForExtension:(MMExtKey)extKey withSelector:(SEL)selector { if (extKey == nil || selector == NULL) { return; } NSMutableDictionary *dicListeners = [m_dicExtensions objectForKey:NSStringFromProtocol(extKey)]; if (dicListeners != nil) { NSMutableSet *selectorImplememters = [dicListeners objectForKey:NSStringFromSelector(selector)]; if (selectorImplememters != nil) { for (NSString *nsClassName in selectorImplememters) {// ServiceCenter根據類名創建對應的觀察者obj [[MMServiceCenter defaultCenter] getService:NSClassFromString(nsClassName)]; } } }}

3、取消登記:
UNREGISTER_EXTENSION(IMessageExt, self);

define UNREGISTER_EXTENSION(ext, obj) \ { \ MMExtension *oExt = [GET_SERVICE(MMExtensionCenter) getExtension:@protocol(ext)]; \ if (oExt) { \ [oExt unregisterExtension:obj]; \ } \ }

UNREGISTER_EXTENSION宏實現里的unregisterExtension方法解析如下:

  • (void)unregisterExtension:(id)oObserver { BOOL bFound = [m_dicObserver unregisterKeyExtension:oObserver];}- (BOOL)unregisterKeyExtension:(id)oObserver { BOOL bFound = NO;// 遍歷一個協議所有的方法 for (NSArray *selectorImplememters in [m_dic allValues]) {// 遍歷一個方法所有的觀察者 for (MMExtensionObject *extObj in selectorImplememters) { if ([extObj isObjectEqual:oObserver]) { extObj.m_deleteMark = YES; // 只是標記刪除 bFound = YES; break; } } } return bFound;}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 終于把前面的base文件夾簡簡單單的看了一遍,終于可以回到正片上來了,保證不爛尾。 項目天天用yymodel解析數...
    充滿活力的早晨閱讀 1,393評論 1 0
  • 轉至元數據結尾創建: 董瀟偉,最新修改于: 十二月 23, 2016 轉至元數據起始第一章:isa和Class一....
    40c0490e5268閱讀 1,774評論 0 9
  • Objective-C語言是一門動態語言,它將很多靜態語言在編譯和鏈接時期做的事放到了運行時來處理。這種動態語言的...
    有一種再見叫青春閱讀 610評論 0 3
  • 原文出處:南峰子的技術博客 Objective-C語言是一門動態語言,它將很多靜態語言在編譯和鏈接時期做的事放到了...
    _燴面_閱讀 1,258評論 1 5
  • javascript Array 1. Properties Array.length var arr = ["a...
    echo_me閱讀 174評論 0 0