常見的通信方式
首先旗扑,對(duì)OC中常見的通訊方式我們做一個(gè)對(duì)比(KVC與KVO不在討論范圍):
代理 | 通知 | Block | |
---|---|---|---|
適用范圍 | 一對(duì)一 | 一對(duì)多 | 一對(duì)一 |
使用方式 | 方法調(diào)用 | 通知名(字符串)監(jiān)聽 | 屬性缀拭、方法參數(shù)涕癣、全局變量 |
是否允許返回值 | YES | NO | YES |
是否具有封閉性 | YES | NO | YES |
假如我們需要一種可以一對(duì)多,同時(shí)又需要有返回值(或者出于安全性考慮不希望公開)的情況,通知就不適用了,考慮下面的情形:
- 使用一個(gè)單例控制藍(lán)牙連接斷開等狀態(tài)专普,但是有好幾個(gè)類都需要監(jiān)聽藍(lán)牙的狀態(tài)?
- 希望App能夠一鍵切換主題弹沽?
- 異步加載多種資源檀夹,想獲取總的加載進(jìn)度筋粗?
多播代理
C#中有一種委托形式稱作多播委托,會(huì)順序執(zhí)行多個(gè)委托對(duì)象的對(duì)應(yīng)函數(shù)炸渡。
OC中系統(tǒng)并沒有提供類似的類型讓我們使用娜亿,所以需要自己實(shí)現(xiàn)類似的功能。
多播代理相對(duì)于通知的優(yōu)勢(shì)
多播代理 | 通知 | |
---|---|---|
接收范圍 | 定點(diǎn)投放蚌堵,只有已添加的代理可以接收到消息 | 全局都可接收暇唾,會(huì)暴露實(shí)現(xiàn)細(xì)節(jié),廣播出的參數(shù)中可能包含敏感信息 |
使用方式 | 方法調(diào)用辰斋,使用協(xié)議來約束代理者的方法實(shí)現(xiàn) | 通知名(字符串)監(jiān)聽,容易出現(xiàn)問題瘸味,當(dāng)項(xiàng)目中大量使用通知以后難以維護(hù)宫仗,極端情況會(huì)出現(xiàn)通知名重復(fù)的問題 |
是否允許返回值 | YES | NO |
是否具有封閉性 | YES | NO |
多播代理的實(shí)現(xiàn)思路
1.存儲(chǔ)多個(gè)代理對(duì)象
OC中常規(guī)代理通常使用弱引用來避免循環(huán)引用,因此我們的多播代理中也需要使用能夠存儲(chǔ)弱引用對(duì)象的容器旁仿,這里有幾種思路:
- 使用NSValue的
valueWithNonretainedObject:
方法將對(duì)象打包藕夫,然后將打包后的NSValue對(duì)象添加到代理數(shù)組中。 - 創(chuàng)建一個(gè)新的類枯冈,在這個(gè)類中對(duì)代理對(duì)象進(jìn)行弱引用(實(shí)質(zhì)是對(duì)上一個(gè)思路的手動(dòng)實(shí)現(xiàn))毅贮。然后再將這個(gè)新類的實(shí)例添加到代理數(shù)組中。
- 使用NSHashTable存儲(chǔ)代理對(duì)象尘奏,我們用到一個(gè)比較不常見的容器:NSHashTable
NSHashTable
iOS6以后滩褥,F(xiàn)oundation框架中新增了容器類:NSHashTable —— 它是可變的,沒有一個(gè)不變的類與其對(duì)應(yīng)炫加。它的作用對(duì)應(yīng)于NSMutableSet瑰煎,但是它可以通過設(shè)置NSPointerFunctionsOptions
參數(shù)來指定對(duì)象的引用類型:
NSHashTableStrongMemory:將容器內(nèi)的對(duì)象引用計(jì)數(shù)+1一次(即strong)
NSHashTableCopyIn:將添加到容器的對(duì)象通過NSCopying中的方法,復(fù)制一個(gè)新的對(duì)象存入容器(即copy)
NSHashTableZeroingWeakMemory:使用weak存儲(chǔ)對(duì)象俗孝,當(dāng)對(duì)象被銷毀的時(shí)候自動(dòng)將其從集合中移除酒甸。(已棄用)
NSHashTableObjectPointerPersonality: 使用移位指針(shifted pointer)來做hash檢測(cè)及確定兩個(gè)對(duì)象是否相等(而不是使用NSObject中的hash方法)
NSHashTableWeakMemory:不會(huì)修改容器內(nèi)對(duì)象元素的引用計(jì)數(shù),并且對(duì)象釋放后赋铝,會(huì)被自動(dòng)移除(即weak)
ps NSHashTableWeakMemory的對(duì)象釋放后插勤,NSHashTable中其實(shí)是置空(NSHashTable可以保存空對(duì)象),但遍歷時(shí)不會(huì)遍歷到該對(duì)象革骨,相對(duì)于移除了农尖。
2.添加代理對(duì)象
基于上面的選擇,我們使用 NSHashTable 來管理存儲(chǔ)和遍歷代理對(duì)象苛蒲,因此需要公開一個(gè)添加代理的方法:
- (void)addDelegate:(id <xxxProtocol>)newDelegate;
3.調(diào)用代理方法
調(diào)用常規(guī)代理時(shí)卤橄,通常需要寫以下寫法:
if ([delegate respondsToSelector:@selector(<#方法名#>:)]) {
[delegate <#方法名#>:<#參數(shù)#>];
}
那么假如我們的代理協(xié)議中有多個(gè)方法,我們就需要對(duì)每個(gè)代理方法都寫一次這樣的代碼臂外,相當(dāng)繁瑣窟扑。
通常的簡(jiǎn)化方法是利用OC的消息轉(zhuǎn)發(fā)機(jī)制喇颁,在方法轉(zhuǎn)發(fā)過程中進(jìn)行消息轉(zhuǎn)發(fā)。
簡(jiǎn)單的多播代理流程
基于以上的思路嚎货,我們可以有一個(gè)大致的流程圖:
改進(jìn)方案
上面的方案實(shí)現(xiàn)了簡(jiǎn)單的多播代理橘霎,但是有一些缺陷:
- 如果該MutableDelegate類中有一個(gè)方法和代理協(xié)議中定義的方法同名,將導(dǎo)致消息轉(zhuǎn)發(fā)的過程不會(huì)觸發(fā)殖属。
- 如果項(xiàng)目中需要用到多個(gè)多播代理姐叁,則需要實(shí)現(xiàn)多次上面的方法
- 多線程問題
1. 定義多代理轉(zhuǎn)發(fā)類
這個(gè)類用來封裝多代理實(shí)現(xiàn),我們使用NSProxy子類來實(shí)現(xiàn)它:
@interface MulitiDelegate : NSProxy
/**
創(chuàng)建
@return MulitiDelegate對(duì)象
*/
+ (instancetype)new;
/**
添加代理
*/
- (void)addDelegate:(id)delegate;
/**
移除代理
*/
- (void)removeDelete:(id)delegate;
@end
2. 處理多線程同步問題
使用信號(hào)量解決多線程集合對(duì)象的同步問題:
//...
/// 信號(hào)量
@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 - 消息轉(zhuǎn)發(fā)部分
- (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;
}
// 未找到方法時(shí)洗显,返回默認(rèn)方法 "- (void)method"外潜,防止崩潰
return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}
- (void)forwardInvocation:(NSInvocation *)invocation {
dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
// 為了避免造成遞歸死鎖,copy一份delegates而不是直接用信號(hào)量將for循環(huán)包裹
NSHashTable *copyDelegates = [_delegates copy];
dispatch_semaphore_signal(_semaphore);
SEL selector = invocation.selector;
for (id delegate in copyDelegates) {
if ([delegate respondsToSelector:selector]) {
// 異步調(diào)用時(shí)挠唆,拷貝一個(gè)Invocation处窥,以免意外修改target導(dǎo)致crash
NSInvocation *dupInvocation = [self copyInvocation:invocation];
dupInvocation.target = delegate;
// 異步調(diào)用多代理方法,以免響應(yīng)不及時(shí)
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;
}
使用方式
這里用一個(gè)簡(jiǎn)單的一鍵切換主題的例子來說明多播代理的使用方式:
主題管理器(ThemesManager)
創(chuàng)建一個(gè)單例主題管理器來管理我們的主題顏色玄组,并能夠添加和移除代理:
@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文件中需要實(shí)現(xiàn)單例(單例的代碼建議定義成一個(gè)通用的宏定義,方便其他地方一起使用)俄讹,然后使用之前定義的多播代理來進(jìn)行“廣播”:
#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) {
// 默認(rèn)顏色
_themesColor = [UIColor colorWithWhite:0.8f alpha:1.f];
}
return _themesColor;
}
@end
控制器們
通常我們會(huì)有一個(gè)專門的改變主題的界面和一些其他界面哆致,這里就簡(jiǎn)單的使用同一個(gè)界面跳轉(zhuǎn)和改變主題顏色:
#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 {
// 生成隨機(jī)顏色
CGFloat hue = arc4random() % 100 / 100.0; //色調(diào):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創(chuàng)建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{
// 需要注意的是這里是異步調(diào)用,改變顏色需要在主線程
dispatch_async(dispatch_get_main_queue(), ^{
self.view.backgroundColor = themesColor;
});
}
@end
調(diào)用流程
運(yùn)行效果
最后加上返回值的獲取代碼患膛,主要就是如何存儲(chǔ)和判斷類型摊阀,這里就不贅述了。
目前已開源到GitHub上踪蹬,并支持pods使用啦~