IOS觀察者模式_NSNotification,KVO,Delegate的使用理解

個人對IOS觀察者模式的理解,就是一個被觀察的對象和一個觀察對象,其實總覺得觀察這個詞不是很準確,通知這個詞更爲準確,三種方法中,除了NSNotification是廣播似的傳播消息外,KVO和Delegate都是一對一的傳播,Delegate大家已經用得很熟了,我只說說NSNotification和Delegate,其實是Delegate用得熟悉,但是說着就很繞了,而且還不一定說得清楚。


NSNotifiction

該方式是相對簡單地,不用對象之間的相互引用,只有在同一個應用程序內,都能夠通知得到,只要notifictionWithName相同,所有觀察着都能被通知到


註冊一個被監聽對象,newNotification是被監聽對象識別的標識,object是傳出的參數

[[NSNotificationCenter defaultCenter] postNotificationName:@"newNotification" object:@"change"];

或者

NSNotification *notification=[NSNotificationnotificationWithName:@"newNotification"object:@"change"];

 [[NSNotificationCenter defaultCenter] postNotification:notification];

註冊一個監聽者

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationCenter:) name:@"newNotification" object:nil];

//接到通知後調用的方法

- (void)notificationCenter:(NSNotification *)notification

{

    NSString *string=(NSString *)notification;

    NSLog(@"%@",string);

}


//下面是輸出內容

{name = newNotification; object = change}


KVO --Key-Value Observing Programming Guide


通過KVO,某個對象中的特定屬性發生了改變,別的對象可以獲得通知,幾乎在OC裏面每一個類都存在這兩個方法

- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;


//給對象添加一個監視器,在keyPath屬性做出相應地options動作後就會調用observer類的方法observeValueForKeyPath: ofObject: change:e context:


//聲明一個內 存在changeable屬性

@interface KVOSubject : NSObject

@property (nonatomic,strong) NSString *changeable;

@end


@implementation KVOSubject

@end


在當前當前對象觸發方法內實例KVOSubject

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

KVOSubject *kvoSubj = [[KVOSubject alloc] init];

    [kvoSubj addObserver:self forKeyPath:@"changeable"  options:NSKeyValueObservingOptionNew context:nil];

    kvoSubj.changeable = @"新的一個值";

    [kvoSubj setValue:@"新的一個值" forKey:@"changeable"];

    [kvoSubj removeObserver:self forKeyPath:@"changeable"];

}

//當觸發屏幕後該類就會被調用

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

   NSLog(@"%@",keyPath);

}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章