何时使用NSNotificationCenter

Eta*_*tan 13 architecture objective-c nsnotificationcenter ios observer-pattern

我希望在一个对象的多个事件上有多个观察者(1对N关系).

实现这一任务的机制由提供NSNotificationCenter.当用于我的问题时,该机制看起来相当矫枉过正.

如何在不使用以下情况下手动完成NSNotificationCenter:

- (void)addDelegate:(id<DelegateProtocol>)delegate;
- (void)removeDelegate:(id<DelegateProtocol>)delegate;
Run Code Online (Sandbox Code Playgroud)

从我的对象添加和删除观察者.

- (void)someEventFired:(NSObject<NSCopying> *)eventData
{
    for (id delegate in delegates) {
        NSObject *data = [eventData copy];
        [delegate someEventFired:data];
    }
}
Run Code Online (Sandbox Code Playgroud)

这种机制是直接的,易于实现,而对象不必共享其他字符串.

  • 除了NSNotificationCenter?之外,iOS框架中是否存在1对N代表(如C#事件)的官方模式?
  • 什么时候应该NSNotificationCenter使用,何时不使用?
  • 什么时候应该使用像我在这里建议的实现,什么时候不使用?

Seb*_*lis 14

按照惯例,代表应该只用于1:1的关系.如果您真的需要此类功能的1:N关系,您有两种选择:

  1. 如你所说,NSNotificationCenter.
  2. 键值观察(也称为KVO).

如果您只关心对象的特定属性何时发生变化,那么KVO是合适的.否则,你应该考虑使用NSNotificationCenter.只有当特定对象通过将该对象传递给addObserver:selector:name:object:方法来发布该通知时,才能通知您.

苹果使用NSNotification在类似的情况下(像定义的通知UITextField,包括UITextFieldTextDidBeginEditingNotification,UITextFieldTextDidChangeNotificationUITextFieldTextDidEndEditingNotification).