NSNotificationCenter vs delegation( using protocols )?

前端 未结 6 642
天涯浪人
天涯浪人 2020-11-27 10:56

What are the pros and cons of each of them?
Where should I use them specifically?

6条回答
  •  情书的邮戳
    2020-11-27 11:36

    Considering the performance is a good idea (delegation better for small number of notified objects, notification centre better for larger number of objects, or is it? run a profiler) but I think a more important factor since you are talking about Objective-C and less likely to be talking about the really high performance parts of your code base, which are likely to be written in C, is reducing compile-time dependencies between modules.

    There is nothing to stop you having an array of delegates rather than a single delegate.

    I might use NSNotificationCenter only for status of any network stack components I make and any custom device status monitoring interfaces. But for most coupling, not to do with global status of the app, I think it is clearer to use normal interface contracts in Objective-C in most cases and easier to folow for the people coming after you than to use NSNotificationCenter. In fact I have never used NotificationCenter for my own custom events and prefer to use delegates for ease of code comprehension by someone else reading my code.

    And finally, of course with notifications to/from the standard API you don't have choice and must use whichever of the two methods Apple proscribe for a given event.

提交回复
热议问题