iOS 中的消息传递方法主要有
- KVO
- delegation
- NSNotification
- block
- target-action
这里简单记录下一些用法。
KVO
KVO 键值监听提供了一种监听机制,当监听的对象的属性发生改变时监听者会收到消息通知,其实现的根本是 OC 的动态性和 Runtime。
这里要注意的是被监听的对象的属性变化只有通过 setter 方法改变才能发出消息通知, 比如用成员变量进行复制是无法被监听到的,对于数组、字典等改变其中某些元素的操作也是不能被监听到的。
实现一个 KVO 监听步骤如下
-
注册观察者
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context;
这个方法一般由被观察的对象调用,其中 observer 是观察者,keyPath 是被观察者的属性,options 有多个选项可以选择。
- NSKeyValueObservingOptionNew: 指示change字典中包含新属性值
- NSKeyValueObservingOptionOld: 指示change字典中包含旧属性值
- NSKeyValueObservingOptionInitial:注册之后立刻调用接收方法,如果配置了NSKeyValueObservingOptionNew,change参数内容会包含新值,键为:NSKeyValueChangeNewKey
- NSKeyValueObservingOptionPrior:如果加入这个参数,接收方法会在变化前后分别调用一次,共两次,变化前的通知change参数包含notificationIsPrior = 1。其他内容根据NSKeyValueObservingOptionNew和NSKeyValueObservingOptionOld的配置确定
这个选项挺复杂的,一般用前两个就足够了。context 是用来区分观察者的,比如父类和子类同时监听同一个对象的属性的时候,可以用判断 context 的方法区别响应。
-
在回调方法中响应观察到的变化
- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSKeyValueChangeKey, id> *)change context:(nullable void *)context;
这里参数与注册时对应,但是由于只有这一个回调方法,所以逻辑代码很容易臃肿,要写很多 if 判断来区别不同的被观察者。
-
移除观察
使用完 KVO 要手动移除观察。
-(void)removeObserver:(NSObject*)observer forKeyPath:(NSString*)keyPath context:(void *)context; -(void)removeObserver:(NSObject*)observer forKeyPath:(NSString*)keyPath;
delegation
委托者利用协议 protocol 可以设定一些公开方法,可委托对象实现这些协议,将可委托对象提供给委托者,就可以供委托者调用,这种通信方式由于方法有返回值,所以是双向的,当然也是一对一的。
为了避免隐藏的循环引用问题,我们一般设置可委托对象如下
@property (nonatomic, weak, nullable) id <UITableViewDataSource> dataSource;
@property (nonatomic, weak, nullable) id <UITableViewDelegate> delegate;
NSNotification
NSNotification 是一个类似 Android 中的广播机制的东西,也可以实现监听和响应等操作,也是一对多的通信,与 KVO 的区别是响应者不知道消息发出者,并且对于消息发送者的侵入较大,因为要主动发出消息。
基本步骤是注册通知、发送广播、注销通知。
注册通知
- 方法一
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
这里 observer 是观察者,selector 是响应方法的选择器,name 和 object 用于唯一确定一条通知。
响应方法可以带一个参数 NSNotification。
-(void)react:(NSNotification *)notification{}
- 方法二
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(responseNotification) name:@"center" object:@"notification"];
这里将方法选择器用 block 代替了,同时还可以指定在哪一个 NSOperationQueue 上执行 block。
[[NSNotificationCenter defaultCenter] addObserverForName:@"center" object:@"notification" queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
NSLog(@"receieve notification");
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"center" object:@"notification"];
}];
发送通知
- 方法一
[[NSNotificationCenter defaultCenter] postNotificationName:@"center" object:@"notification"];
- 方法二
NSDictionary *userInfo = @{@"user": @"info"};
[[NSNotificationCenter defaultCenter] postNotificationName:@"center" object:@"notification" userInfo:userInfo];
- 方法三
NSDictionary *userInfo = @{@"user": @"info"};
NSNotification *notification = [NSNotification notificationWithName:@"center" object:@"notification" userInfo:userInfo];
[[NSNotificationCenter defaultCenter] postNotification:notification];
userInfo 是可选的传递参数,可以在响应函数的
NSNotification 参数中获得。
注销通知
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;
iOS9 以后不需要手动移除。
NSNotificationQueue
上面用的是 NSNotificaionCenter 发送消息是同步的,也就是会阻塞当前线程,直到接收者处理了这个消息,而 NSNotificationQueue 则是异步的,发送操作可以立刻返回,同时 NSNotificationQueue 还可以聚合通知,以避免重复发送的情况。
具体发送时调用以下方法
- (void)enqueueNotification:(NSNotification *)notification postingStyle:(NSPostingStyle)postingStyle;
- (void)enqueueNotification:(NSNotification *)notification postingStyle:(NSPostingStyle)postingStyle coalesceMask:(NSNotificationCoalescing)coalesceMask forModes:(nullable NSArray<NSRunLoopMode> *)modes;
第一个方法没有使用聚合策略,postingStyle 参数有三个枚举项
typedef NS_ENUM(NSUInteger, NSPostingStyle) {
NSPostWhenIdle = 1,
NSPostASAP = 2,
NSPostNow = 3
};
其中 NSPostNow 就是同步发送,NSPostASAP 是尽快发送,NSPostWhenIdle 是 runloop 空闲时发送。
第二个方法的 coalesceMask 可以指定聚合策略,也有三个枚举项
typedef NS_OPTIONS(NSUInteger, NSNotificationCoalescing) {
NSNotificationNoCoalescing = 0,
NSNotificationCoalescingOnName = 1,
NSNotificationCoalescingOnSender = 2
};
分别是不聚合、按照 Name 聚合、按照发送者聚合,不建议过度依赖这个策略。
block
block 本质上是一个变量,类似于给一个对象的属性赋值,但是 block 是一个特殊的变量,它可以像函数一样执行,这样就可以实现类似回调函数的特性,在 block 中实现较多的逻辑和数据处理后返回。所以 block 通信是双向的,消息接受者知道并且持有发送者对象,一般用于子 controller 向父 controller 通信的情况。
我们可以在子 controller 头文件定义一个 block,
typedef void (^MyBlock)(NSString *);
@property(copy, nonatomic) MyBlock block;
为什么是 copy。
但是我们不需要定义这个 block 的具体实现,这件事交给消息接受者(在这里就是父 controller),我们只要在合适的位置直接调用它。
self.block(@"I am second controller");
最后将定义工作放在接受者内
controller.block = ^(NSString *str)
{
NSLog(@"%@", str);
};
这样就实现了通信的过程。
但是如果忘记了初始化、就可能因为 block 为空而 crash 掉。
target-action
这一机制通常用于 View 与 Controller 通信当中,主要利用选择器和 SEL 来实现对方法的调用。