通知,代表和协议之间有什么区别?

er.*_*app 3 iphone notifications delegates protocols objective-c

协议或代表与NSNotifications之间有什么区别?什么是"观察者",它是如何运作的?

jtb*_*des 30

协议

文档:协议

协议是定义对象响应的某些方法的接口.协议的关键是它们可以被任何类采用,保证对象响应这些方法.

如果您声明协议:

@protocol Photosynthesis
@required
- (void)makeFood:(id<Light>)lightSource;
@optional
+ (NSColor *)color; // usually green
@end
Run Code Online (Sandbox Code Playgroud)

然后你可以从其他不一定直接相关的类中采用它:

@interface Plant : Eukaryote <Photosynthesis>
// plant methods...
@end
@implementation Plant
// now we must implement -makeFood:, and we may implement +color
@end
Run Code Online (Sandbox Code Playgroud)

要么

@interface Cyanobacterium : Bacterium <Photosynthesis>
// cyanobacterium methods...
@end
@implementation Cyanobacterium
// now we must implement -makeFood:, and we may implement +color
@end
Run Code Online (Sandbox Code Playgroud)

现在,在其他地方,如果我们只关心协议的一致性,我们可以互换使用这些类中的任何一个:

id<Photosynthesis> thing = getPhotoautotroph(); // can return any object, as long as it conforms to the Photosynthesis protocol
[thing makeFood:[[Planet currentPlanet] sun]]; // this is now legal
Run Code Online (Sandbox Code Playgroud)

代表和通知

文档:Cocoa设计模式

这是在对象之间传递消息的两种方法.主要区别:

  • 对于代理,一个指定对象接收消息.
  • 任何数量的对象在发布时都可以收到通知.

代表通常使用协议来实现:类通常会有类似的东西

@property (weak) id<MyCustomDelegate> delegate;
Run Code Online (Sandbox Code Playgroud)

它为代表提供了一组实现的方法.您可以使用

myObject.delegate = /* some object conforming to MyCustomDelegate */;
Run Code Online (Sandbox Code Playgroud)

然后该对象可以向其委托发送相关消息.有关常见示例,请参阅UITableViewDelegate协议.

另一方面,通知使用NSNotificationCenter实现.对象(或多个对象)只是将自身添加为特定通知的观察者,然后在由另一个对象发布时可以接收它们.

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(notificationHappened:)
                                             name:MyCustomNotificationName
                                           object:nil];
Run Code Online (Sandbox Code Playgroud)

然后就实施吧

- (void)notificationHappened:(NSNotification *)notification {
    // do work here
}
Run Code Online (Sandbox Code Playgroud)

您可以使用任何地方发布通知

[[NSNotificationCenter defaultCenter] postNotificationName:MyCustomNotificationName
                                                    object:self
                                                  userInfo:nil];
Run Code Online (Sandbox Code Playgroud)

并确保removeObserver:在完成后打电话!

  • 一口大小的完整文档+简单示例.赞赏.喜欢光合作用的例子. (4认同)

mal*_*ois 5

您可以通过在stackoverflow中搜索找到答案...