iphone - 通知、委托(delegate)和协议(protocol)之间有什么区别?

标签 iphone objective-c delegates notifications protocols

Protocols or Delegates 和 NSNotifications 有什么区别?什么是“观察者”及其工作原理?

最佳答案

协议(protocol)

文档:Protocols

协议(protocol)是定义对象响应的某些方法的接口(interface)。协议(protocol)的关键在于它们可以被任何类采用,从而保证对象响应这些方法。

如果你声明一个协议(protocol):

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

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

@interface Plant : Eukaryote <Photosynthesis>
// plant methods...
@end
@implementation Plant
// now we must implement -makeFood:, and we may implement +color
@end

@interface Cyanobacterium : Bacterium <Photosynthesis>
// cyanobacterium methods...
@end
@implementation Cyanobacterium
// now we must implement -makeFood:, and we may implement +color
@end

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

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

委托(delegate)和通知

文档:Cocoa Design Patterns

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

  • 通过委托(delegate),一个指定的对象接收一条消息。
  • 任何数量的对象在发布时都可以收到通知。

委托(delegate)通常使用协议(protocol)来实现:一个类通常会有类似的东西

@property (weak) id<MyCustomDelegate> delegate;

它为委托(delegate)提供了一组特定的方法来实现。你可以使用

myObject.delegate = /* some object conforming to MyCustomDelegate */;

然后该对象可以将相关消息发送给它的委托(delegate)。有关一个很好的常见示例,请参阅 UITableViewDelegate protocol .

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

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(notificationHappened:)
                                             name:MyCustomNotificationName
                                           object:nil];

然后就实现

- (void)notificationHappened:(NSNotification *)notification {
    // do work here
}

而且您可以使用

从任何地方发布通知
[[NSNotificationCenter defaultCenter] postNotificationName:MyCustomNotificationName
                                                    object:self
                                                  userInfo:nil];

并确保在完成后调用 removeObserver:!

关于iphone - 通知、委托(delegate)和协议(protocol)之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7118598/

相关文章:

ios - 正确检查 NSDictionary 结构

objective-c - iOS 过早释放对象 - 可能与 Autorelease 和 Copy 混淆

ios - 无法在 iPhone X 上将界面方向旋转为纵向颠倒

ios - 禁用一半的 UIStepper

.net - 为什么构造的委托(delegate)类的调用方法是虚拟的?

ios - 即使条件为假,代码也会执行

iphone - 如何在 iOS 的 UIWebView 中获取所选文本和图像的 HTML 代码?

ios - 文本字段在填充数据后未格式化

ios - 自定义 uitextfield 的保留周期(强引用)修复?

iphone - 具有非 GPL 许可的 iOS 的 SIP 库