IOS design pattern-Observer Pattern
Observer mode:
Defines a one-to-many dependency between objects. When the status of an object changes, all objects dependent on it are notified and automatically updated.
When to use observer Mode
(1): changing an object requires changing other objects at the same time without knowing how many objects need to be changed.
(2): An object must notify other objects without knowing what other objects are.
(3) Two abstract types are mutually dependent. By encapsulating them in their own objects, they can be changed and reused separately.
Use the observer mode in the Cocoa Touch framework
1: Notification Type:
The nsicationicationcenter and NSNotification objects are used for one-to-many interaction, allowing the target and the observer to communicate in a coupled manner, while the two do not need to know much about them.
For example, the Model constructs a notification to be placed in the notification center:
NSNotification * notification = [NSNotification notificationWithName: @ "data change" object: self];
Nsicationicationcenter * notificationCenter = [NSNotificationCenter defacenter center];
[Icationicationcenter postNotification: notification];
Anyone who wants to subscribe to this notification must first register for himself.
[Icationcenter center addObserVer: self
Selector: @ selector (update :)
Name: @ "data change"
Object: subject];
2: Key-value observation
This mechanism is based on the NSKeyValueObserving informal Protocol, through which Cocoa provides an automated property observation capability for all objects that comply with the Protocol. based on informal protocols, KVC automatically observes object attributes through access.
/* Register the Observer */
[_ WalkeraddObserver: selfforKeyPath: @ ageoptions: NSKeyValueObservingOptionNewcontext: nil];
/* KVO function calls this function as long as the object's keyPath attribute changes */
-(Void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context