What is the difference between Protocols or Delegates and NSNotifications? What is an "Observer" and how does it work?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- back button text does not change
相关文章
- 现在使用swift开发ios应用好还是swift?
- Could I create “Call” button in HTML 5 IPhone appl
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- How do you detect key up / key down events from a
- “Storyboard.storyboard” could not be opened
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!You can find answers by searching in stackoverflow ...