Notification Queue
有的时候,我们的程式可能会在很短的时间送出大量的notification,而造成资源的浪费或性能问题。
以KKBOX 来说,我们在歌单中的歌曲实例发生改动的时候,会透过notification 更新UI:一首歌曲可能会出现在多个歌单中,而我们可能用了很多不同的UI 控件来呈现不同张歌单,因此,像一首歌曲的播放次数改变、如这首歌被多播放了一次,歌曲控件就透过notification center,告诉每个跟歌单UI 相关的控件重新读取歌单资料。
照理说,只要有一首歌曲改变,就该发出这种通知,但假如我们现在做的事情是歌单同步—把另外一台装置上的歌单资料,同步到我们这台装置上,那么改动的就不只是一首歌曲,而是一大批的歌曲,如果有十首歌,就送出了十次通知;但是,其实UI 只需要改动一次就好了,没有重复更新十次UI 的必要。
这时候我们就该用NSNotificationQueue。我们可以把NSNotificationQueue 想成notification 的发送端与notification center 之间的一个buffer,这个buffer 可以让我们暂缓送出notification,而在一段缓冲期之内,决定我们是否要合并通知。以前面的例子来看,我们就可以先把原本预计的十次通知先放进NSNotificationQueue 当中,然后让NSNotificationQueue 帮我们把十次通知合并成只有一次通知。
我们要先建立一个NSNotificationQueue 实例:
notificationQueue = [[NSNotificationQueue alloc]
initWithNotificationCenter:[NSNotificationCenter defaultCenter]];
再来我们发送通知的程式原本像这样:
NSNotification *n = [NSNotification
notificationWithName:@"KKSongInfoDidChangeNotification"
object:self];
[[NSNotificationCenter defaultCenter] postNotification:n];
改写成这样:
NSNotification *n = [NSNotification
notificationWithName:@"KKSongInfoDidChangeNotification"
object:self];
[notificationQueue enqueueNotification:n
postingStyle:NSPostASAP
coalesceMask:NSNotificationCoalescingOnName | NSNotificationCoalescingOnSender
forModes:nil];
我们在这边传入了NSNotificationCoalescingOnName
与NSNotificationCoalescingOnSender
,代表的就是请notification queue合并名称相同、发送者也相同的通知。