ios - 多播代理和通知的优缺点
大家讲道理
大家讲道理 2017-04-18 09:24:50
0
1
480

为什么我们使用多播代理而不使用通知呢?
多播代理的具体应用场景有哪些?
求大神指导

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(1)
左手右手慢动作

Good question.
1. The explanation I learned is: notifications will cause interference. For example, if you want to download three pictures A, B, and C, and A is finished downloading, a notification will be sent, and the places where pictures B and C are waiting for notifications will also receive it, but In fact, they don't need to.

I feel that this problem can be solved. Just add the corresponding identification to each task. For example, in the case of downloading images above, the notification name is set to "loadImage_" + the last section of the url. And the notification can specify the sender

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSString *)aName object:(nullable id)anObject;

最后一个参数就是指定发送者

2. I think it can be used casually. There are some advantages to using a proxy: the method name of the delegate is already defined, the interface definition is clear, and you know what parameters to pass, which is better for collaborative development or wheel-building. Notifications generally rely on userinfo to pass parameters. This is a dictionary with no specified type. The data structure inside is not sure, and it is not very clear.

3. In fact, I think it is best to use block or closure.

  • Multiple delegates need to be added to the array, resulting in strong references and possible circular reference problems.

  • I think block is easier to write. You can write the callback code next to it, such as downloading pictures,

var name:string = "xxx"
downloadImageWithCompleteHander:{
    //回调后的逻辑可以直接写在这里
    //可以直接使用这个临时变量name,因为block的copy性质
}

As for delegation, you have to write another method, especially if some parameters need to be passed. When using delegate, you have to turn those temporary variable pages into member variables, otherwise they cannot be used across methods

  • The last block has good isolation properties.
    For example, if you use a single instance to manage all image downloads, assuming it is called loadManager, if you use multiple delegates, you still need to distinguish between different download tasks, because all download tasks go to one thing, loadManager, and its multi-delegate list It contains the delegation of different download tasks, but still needs to be distinguished. But using blocks, they can be naturally isolated. The explanation is more complicated, that is, blocks are nested in each other and isolated from the beginning. It will be clear if you look at the code of SDWebImage.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template