【OC梳理】多播代理
首先,對OC中常見的通訊方式我們做一個對比(KVC與KVO不在討論範圍):
代理 | 通知 | Block | |
---|---|---|---|
適用範圍 | 一對一 | 一對多 | 一對一 |
使用方式 | 方法呼叫 | 通知名(字串)監聽 | 屬性、方法引數、全域性變數 |
是否允許返回值 | YES | NO | YES |
是否具有封閉性 | YES | NO | YES |
假如我們需要一種可以一對多,同時又需要有返回值(或者出於安全性考慮不希望公開)的情況,通知就不適用了,考慮下面的情形:
- 使用一個單例控制藍芽連線斷開等狀態,但是有好幾個類都需要監聽藍芽的狀態?
- 希望App能夠一鍵切換主題?
- 非同步載入多種資源,想獲取總的載入進度?
多播代理
C#中有一種委託形式稱作多播委託,會順序執行多個委託物件的對應函式。 OC中系統並沒有提供類似的型別讓我們使用,所以需要自己實現類似的功能。
多播代理相對於通知的優勢
多播代理 | 通知 | |
---|---|---|
接收範圍 | 定點投放,只有已新增的代理可以接收到訊息 | 全域性都可接收,會暴露實現細節,廣播出的引數中可能包含敏感資訊 |
使用方式 | 方法呼叫,使用協議來約束代理者的方法實現 | 通知名(字串)監聽,容易出現問題,當專案中大量使用通知以後難以維護,極端情況會出現通知名重複的問題 |
是否允許返回值 | YES | NO |
是否具有封閉性 | YES | NO |
多播代理的實現思路
1.儲存多個代理物件
OC中常規代理通常使用弱引用來避免迴圈引用,因此我們的多播代理中也需要使用能夠儲存弱引用物件的容器,這裡有幾種思路:
- 使用NSValue的
valueWithNonretainedObject:
方法將物件打包,然後將打包後的NSValue物件新增到代理陣列中。 - 建立一個新的類,在這個類中對代理物件進行弱引用(實質是對上一個思路的手動實現)。然後再將這個新類的例項新增到代理陣列中。
- 使用NSHashTable儲存代理物件,我們用到一個比較不常見的容器: NSHashTable
NSHashTable
iOS6以後,Foundation框架中新增了容器類:NSHashTable —— 它是可變的,沒有一個不變的類與其對應。它的作用對應於NSMutableSet,但是它可以通過設定 NSPointerFunctionsOptions
引數來指定物件的引用型別:
NSHashTableStrongMemory:將容器內的物件引用計數+1一次(即strong) NSHashTableCopyIn:將新增到容器的物件通過NSCopying中的方法,複製一個新的物件存入容器(即copy) NSHashTableZeroingWeakMemory:使用weak儲存物件,當物件被銷燬的時候自動將其從集合中移除。(已棄用) NSHashTableObjectPointerPersonality: 使用移位指標(shifted pointer)來做hash檢測及確定兩個物件是否相等(而不是使用NSObject中的hash方法) NSHashTableWeakMemory:不會修改容器內物件元素的引用計數,並且物件釋放後,會被自動移除(即weak) 複製程式碼
ps NSHashTableWeakMemory的物件釋放後,NSHashTable中其實是置空(NSHashTable可以儲存空物件),但遍歷時不會遍歷到該物件,相對於移除了。
2.新增代理物件
基於上面的選擇,我們使用 NSHashTable 來管理儲存和遍歷代理物件,因此需要公開一個新增代理的方法:
- (void)addDelegate:(id <xxxProtocol>)newDelegate; 複製程式碼
3.呼叫代理方法
呼叫常規代理時,通常需要寫以下寫法:
if ([delegate respondsToSelector:@selector(<#方法名#>:)]) { [delegate <#方法名#>:<#引數#>]; } 複製程式碼
那麼假如我們的代理協議中有多個方法,我們就需要對每個代理方法都寫一次這樣的程式碼,相當繁瑣。 通常的簡化方法是利用OC的訊息轉發機制,在方法轉發過程中進行訊息轉發。
簡單的多播代理流程
基於以上的思路,我們可以有一個大致的流程圖:

改進方案
上面的方案實現了簡單的多播代理,但是有一些缺陷:
- 如果該MutableDelegate類中有一個方法和代理協議中定義的方法同名,將導致訊息轉發的過程不會觸發。
- 如果專案中需要用到多個多播代理,則需要實現多次上面的方法
- 多執行緒問題
1. 定義多代理轉發類
這個類用來封裝多代理實現,我們使用NSProxy子類來實現它:
@interface MulitiDelegate : NSProxy /** 建立 @return MulitiDelegate物件 */ + (instancetype)new; /** 新增代理 */ - (void)addDelegate:(id)delegate; /** 移除代理 */ - (void)removeDelete:(id)delegate; @end 複製程式碼
2. 處理多執行緒同步問題
使用訊號量解決多執行緒集合物件的同步問題:
//... /// 訊號量 @property ( nonatomic, strong ) dispatch_semaphore_t semaphore; //... /// 初始化 + (id)alloc{ MulitiDelegate *instance = [super alloc]; if (instance) { instance.semaphore = dispatch_semaphore_create(1); instance.delegates = [NSHashTable weakObjectsHashTable]; } return instance; } /// 新增代理 - (void)addDelegate:(id)delegate{ dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER); [_delegates addObject:delegate]; dispatch_semaphore_signal(_semaphore); } /// 移除代理 - (void)removeDelete:(id)delegate{ dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER); [_delegates removeObject:delegate]; dispatch_semaphore_signal(_semaphore); } #pragma mark - 訊息轉發部分 - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER); NSMethodSignature *methodSignature; for (id delegate in _delegates) { if ([delegate respondsToSelector:selector]) { methodSignature = [delegate methodSignatureForSelector:selector]; break; } } dispatch_semaphore_signal(_semaphore); if (methodSignature){ return methodSignature; } // 未找到方法時,返回預設方法 "- (void)method",防止崩潰 return [NSMethodSignature signatureWithObjCTypes:"v@:"]; } - (void)forwardInvocation:(NSInvocation *)invocation { dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER); // 為了避免造成遞迴死鎖,copy一份delegates而不是直接用訊號量將for迴圈包裹 NSHashTable *copyDelegates = [_delegates copy]; dispatch_semaphore_signal(_semaphore); SEL selector = invocation.selector; for (id delegate in copyDelegates) { if ([delegate respondsToSelector:selector]) { // 非同步呼叫時,拷貝一個Invocation,以免意外修改target導致crash NSInvocation *dupInvocation = [self copyInvocation:invocation]; dupInvocation.target = delegate; // 非同步呼叫多代理方法,以免響應不及時 dispatch_async(dispatch_get_global_queue(0, 0), ^{ [dupInvocation invoke]; }); } } } - (NSInvocation *)copyInvocation:(NSInvocation *)invocation { SEL selector = invocation.selector; NSMethodSignature *methodSignature = invocation.methodSignature; NSInvocation *copyInvocation = [NSInvocation invocationWithMethodSignature:methodSignature]; copyInvocation.selector = selector; NSUInteger count = methodSignature.numberOfArguments; for (NSUInteger i = 2; i < count; i++) { void *value; [invocation getArgument:&value atIndex:i]; [copyInvocation setArgument:&value atIndex:i]; } [copyInvocation retainArguments]; return copyInvocation; } 複製程式碼
使用方式
這裡用一個簡單的一鍵切換主題的例子來說明多播代理的使用方式:
主題管理器(ThemesManager)
建立一個單例主題管理器來管理我們的主題顏色,並能夠新增和移除代理:
@protocol ThemesDelegate <NSObject> /// 主題顏色改變 - (void)themesColorChanged:(UIColor *)themesColor; @end @interface ThemesManager : NSObject /// 主題顏色 @property ( nonatomic, copy ) UIColor *themesColor; /// 獲取單例 + (instancetype)sharedManager; /// 新增、移除代理 - (void)addDelegate:(id<ThemesDelegate>)delegate; - (void)removeDelegate:(id<ThemesDelegate>)delegate; @end 複製程式碼
在.m檔案中需要實現單例(單例的程式碼建議定義成一個通用的巨集定義,方便其他地方一起使用),然後使用之前定義的多播代理來進行“廣播”:
#import "ThemesManager.h" #import "MulitiDelegate.h" @interface ThemesManager() /// 多播代理 @property ( nonatomic, strong ) MulitiDelegate *delegateProxy; @end @implementation ThemesManager @synthesize themesColor = _themesColor; static ThemesManager *_manager = nil; + (instancetype)sharedManager{ return [[self alloc]init]; } + (instancetype)allocWithZone:(struct _NSZone *)zone{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if (_manager == nil) { _manager = [super allocWithZone:zone]; } }); return _manager; } - (nonnull id)copyWithZone:(nullable NSZone *)zone { return _manager; } - (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone { return _manager; } - (MulitiDelegate *)delegateProxy{ if (!_delegateProxy) { _delegateProxy = [MulitiDelegate new]; } return _delegateProxy; } - (void)addDelegate:(id<ThemesDelegate>)delegate { [self.delegateProxy addDelegate:delegate]; } - (void)removeDelegate:(id<ThemesDelegate>)delegate { [self.delegateProxy removeDelete:delegate]; } - (void)setThemesColor:(UIColor *)themesColor{ _themesColor = [themesColor copy]; [(id<ThemesDelegate>)self.delegateProxy themesColorChanged:_themesColor]; } - (UIColor *)themesColor{ if (!_themesColor) { // 預設顏色 _themesColor = [UIColor colorWithWhite:0.8f alpha:1.f]; } return _themesColor; } @end 複製程式碼
控制器們
通常我們會有一個專門的改變主題的介面和一些其他介面,這裡就簡單的使用同一個介面跳轉和改變主題顏色:
#import "ThemesManager.h" @interface ViewController ()<ThemesDelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.title = [NSString stringWithFormat:@"%d",self.index]; [[ThemesManager sharedManager]addDelegate:self]; self.view.backgroundColor = [ThemesManager sharedManager].themesColor; } - (IBAction)changeThemes:(id)sender { [ThemesManager sharedManager].themesColor = [self randomColor]; } - (UIColor *)randomColor { // 生成隨機顏色 CGFloat hue = arc4random() % 100 / 100.0; //色調:0.0 ~ 1.0 CGFloat saturation = (arc4random() % 50 / 100) + 0.5; //飽和度:0.5 ~ 1.0 CGFloat brightness = (arc4random() % 50 / 100) + 0.5; //亮度:0.5 ~ 1.0 return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1]; } - (IBAction)nextVC:(id)sender { // 使用Storyboard建立VC UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]]; ViewController *newVC = [story instantiateViewControllerWithIdentifier:@"ViewController"]; newVC.index = self.index + 1; [self.navigationController pushViewController:newVC animated:YES]; } #pragma mark - ThemesDelegate - (void)themesColorChanged:(UIColor *)themesColor{ // 需要注意的是這裡是非同步呼叫,改變顏色需要在主執行緒 dispatch_async(dispatch_get_main_queue(), ^{ self.view.backgroundColor = themesColor; }); } @end 複製程式碼