1. efficiency is certainly delegate higher than Nsnotification.
2. The delegate method is more direct than notification and the most typical feature is the difference between KVO and nsnotification :
Like delegate, the role of KVO and Nsnotification is also a class-to-class communication, unlike the Delegate 1) both are responsible for giving notice, the rest of the matter, so there is no return value; 2) delegate is just one-to-one, And these two can be a couple more. The two also have their own characteristics.
1) Use of KVO:
The addObserver:forKeyPath:options:context is emitted by the Observer : method to add the observer.
Then as long as the keypath value of the Observer changes (note: Simply changing its value will not call this method, only through getters and setters to change the value will trigger the KVO), will be called in The Observer method Observevalueforkeypath:o FObject:change:context:
The observer therefore needs to implement method ObserveValueForKeyPath:ofObject:change:context: to respond to notifications sent by KVO.
-
The code is only implemented in the viewer, the Observer does not add any code, so who listens to who registers, then the response is processed, so that the observer and the observer is fully decoupled, the use of flexibility is simple; but kvo can only detect attributes in a class, And the property name is found through NSString, the compiler will not help you to check the wrong and complete, pure hand knock so it is more error-prone.
-
2) Use of nsnotification
-
The notice here is not sent by the Observer, but by the nsnotificationcenter, and different notifications are distinguished by a unique notification identifier named Notificationname, which is the class from which the notification is sent.
-
First the observer himself in the necessary method A, through method
Postnotificationname:object: to give notice notificationname so that the work on this side of the notification is completed, each A is called, A notification notificationname will be sent.
-
Then who listens for a change, through
[Nsnotificationcenter Defaultcenter] method
AddObserver:selector:name:object: When the observer registers to listen for a notification named Notificationname and then each time a notification of name Notificationname is issued, the listener that registers for monitoring invokes its own defined method Notificationselector to respond.
-
Nsnotification's characteristics, is the need to be observed to take the initiative to give notice, and then the observer registered monitoring and then to respond, more than KVO to send a notification step, but its advantage is not limited to the monitoring of property changes, but also to a variety of changes in the state of monitoring, wide range of monitoring, Use is also more flexible.
(go) differences between Nsnotification, delegate, and Kvo