通知、委托和协议之间有什么区别?
协议或委托和 NSNotifications 之间有什么区别?什么是“观察者”以及它如何工作?
What is the difference between Protocols or Delegates and NSNotifications? What is an "Observer" and how does it work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
协议
文档:协议
协议是定义对象响应的某些方法的接口。协议的关键在于它们可以被任何类采用,从而保证对象响应这些方法。
如果你声明一个协议:
那么你可以从其他不一定直接相关的类中采用它:
或者
现在,在其他地方,如果我们只关心协议的一致性,我们可以互换使用这些类中的任何一个:
委托和协议通知
文档:Cocoa 设计模式< /a>
这是在对象之间传递消息的两种方法。主要区别:
委托通常使用协议来实现:类通常具有类似的东西
,它为委托提供了一组要实现的特定方法。您可以使用
,然后该对象可以向其委托发送相关消息。有关一个很好的常见示例,请参阅 UITableViewDelegate 协议。
另一方面,通知是使用 NSNotificationCenter。一个对象(或多个对象)只需将自身添加为特定通知的观察者,然后可以在另一个对象发布通知时接收它们。
然后只需实现
您就可以使用从任何地方发布通知
并确保在完成后调用
removeObserver:
!Protocols
Documentation: Protocols
Protocols are interfaces which define certain methods that objects respond to. The key thing about protocols is that they can be adopted by any class, guaranteeing that an object responds to those methods.
If you declare a protocol:
Then you can adopt it from other classes which are not necessarily directly related:
or
Now, elsewhere, we can use any of these classes interchangeably, if we only care about conformance to the protocol:
Delegates & Notifications
Documentation: Cocoa Design Patterns
These are two ways to pass messages between objects. The main difference:
Delegates are usually implemented using protocols: a class will usually have something like
which gives the delegate a certain set of methods to implement. You can use
and then the object can send relevant messages to its delegate. For a good common example, see the UITableViewDelegate protocol.
Notifications, on the other hand, are implemented using NSNotificationCenter. An object (or more than one object) simply adds itself as an observer for specific notifications, and then can receive them when they are posted by another object.
Then just implement
And you can post notifications from anywhere using
And make sure to call
removeObserver:
when you're done!您可以通过在 stackoverflow 中搜索来找到答案...
You can find answers by searching in stackoverflow ...