Common iOS design patterns-Observer Design Patterns
Observer Design Patterns
Observer Design Pattern description basic concepts nsicationicationcenter use add listener receive message deletion monitoring KVO use basic concepts register observer object change callback method remove observer identity code implementation
Basic Concepts
The observer mode defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time. When the status of this topic object changes, it notifies all observer objects so that they can automatically update themselves. in IOS development, we may be exposed to the implementation methods of the classic observer mode, such as nsicationicationcenter, KVO, and Delegate.
NSNotificationCenter use add listener (void) addObserver :( id) observer selector :( SEL) aSelector name :( NSString *) aName object :( id) anObject;
Sample:
[[Nsicationcenter center defacenter center] addObserver: self selector: @ selector (doSomething :) name: GET_UP object: nil];
Note:
[Nsicationicationcenter defacenter center] There is only one message center. You can use this method to obtain the singleton of this class.
AddObserver: Add listener
Selector: indicates the processing function after listening to the object.
Name: Indicates registration of the message name of interest receiving the message (void) postNotification :( NSNotification *) notification; (void) postNotificationName :( NSString *) aName object :( id) anObject; (void) postNotificationName :( NSString
) AName object :( id) anObject userInfo :( NSDictionary) AUserInfo;
Sample:
[[Nsicationcenter center defacenter center] postNotificationName: GET_UP object: [NSNumber numberWithInteger: self. time];
Analysis:
GET_UP: name of the push message
Object: the object that sends the message.
UserInfo: delete monitoring (void) removeObserver :( id) observer; (void) removeObserver :( id) observer name :( NSString *) aName object :( id) anObject; basic concepts of KVO
KVO, that is, Key-Value Observing, provides a mechanism. When the attribute of a specified object is modified, the object will receive a notification. This method is very different from NSNotification. It does not require a icationcenter center to provide change notifications for all observers. On the contrary, when a change occurs, the notification is sent directly to the observer, NSObject implements this method for us.
With this method, we can observe the object, which is a one-to-many relationship.
Register an observer
First, you must send
AddObserver: selfforKeyPath: @ "happyNum" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
Context: nil] The message is sent to the observed object, which is used to transmit the Key Path of the observed object and the attribute to be observed. Parameter Analysis:
-(Void) addObserver :( NSObject) Observer forKeyPath :( NSString) KeyPath options :( NSKeyValueObservingOptions) options context :( void *) context;
Observer: indicates the observer, which is generally self.
KeyPath: indicates the object to be observed.
Options: NSKeyValueObservingOptionNew indicates to observe the new value, and NSKeyValueObservingOptionOld indicates to observe the old value.
Context: indicates the context.
Callback method when the observer object changes
(Void) observeValueForKeyPath :( NSString *) keyPath
OfObject :( id) object
Change :( NSDictionary *) change
Context :( void *) context {
NSLog (@ "% @", change );
}
Parameter Analysis:
Change: indicates the value returned when a change occurs.
KeyPath: indicates the observed object.
Contenst: indicates the context
Remove observer identity
Send a set observer object and path to remove the observer. This function is generally placed in dealloc:
[Self. childremoveObserver: selfforKeyPath: @ "happyNum" context: nil];
Code Implementation
child.h#import
@interface Child : NSObject@property(nonatomic,assign)NSInteger happyNum;@endchild.m#import "Child.h"@implementation Child-(id)init{ self=[super init]; if(self) { self.happyNum=100; [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(decrease:) userInfo:nil repeats:YES]; } return self;}-(void)decrease:(NSTimer*)timer{ // NSLog(@"the happyNum is %ld",self.happyNum); _happyNum--; // [self setValue:[NSNumber numberWithInteger:_happyNum] forKey:@"happyNum"];}@endnurse.h#import
#import "Child.h"@interface Nurse : NSObject@property(nonatomic,retain)Child *child;-(id)initWithChild:(Child*)child;@endnurse.m:#import "Nurse.h"@implementation Nurse-(id)initWithChild:(Child*)child{ self=[super init]; if(self) { self.child = child; [self.child addObserver:self forKeyPath:@"happyNum" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; } return self;}- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { NSLog(@"%@",change);}-(void)dealloc{ [self.child removeObserver:self forKeyPath:@"happyNum" context:nil]; [_child release]; [super dealloc];}@endmain.m:#import
#import "Child.h"#import "Nurse.h"int main(int argc, const char * argv[]){ @autoreleasepool { Child *childObj=[[[Child alloc] init] autorelease]; Nurse *nurseObj=[[[Nurse alloc] initWithChild:childObj] autorelease]; [[NSRunLoop currentRunLoop] run]; //[nurseObj release]; } return 0;}