ios基礎之通告

通告就是一個對象將消息發給通告中心,然後通告中心又將此消息發送給感興趣的對象。

每個運行中的程序都有一個NSNotificationCenter的成員變量,功能類似於公告欄,對象註冊關注某個確定的notification,這些註冊對象稱之爲observer,其他的一些對象會給center發送notification,然後通告中心將該notification轉發給所有註冊對該notification感興趣的對象嗎,這些發送的對象稱之爲poster.

通告中心允許同一個程序的不同對象通信,它不能跨越不同的程序,其實通告機制就相當於設計模式中觀擦者模式。Cocoa Touch基礎框架提供了兩個類對象來實現通告機制,分別是NSNotification和NSNotificationCenter。NSNotification對象非常簡單,就是poster提供給observer的信息包裹,notification對象有兩個重要的成員變量:name和object,一般object都是指向poster,在接收notification的時候可以回調poster。

NSNotification有兩個方法:

-(NSSting *name);
-(id)object
NSNotificationCenter允許我們註冊observer對象,發送notification,撤銷observer對象註冊:

常用方法:

+(NSNotificationCenter *)defaultCenter

返回單態實例,Cocoa Touch有很多對象都是通過類似方法實現。

-(void)addObserver:(id)anObserver Selector:(SEL)aselector Name:(NSString *)notificationName Object:(id)anObject
  註冊observer對象:接受對象名字爲notificationName,發送者爲anObject 的notification。當anObject發送notificationName的notification時,將會調用anObserver的aselector方法,參數該爲notification。

如果notificationName爲nil,那麼通過中心將anObject發送的所有notification轉發給observer。

如果observer爲nil,那麼通告中心將所有名字爲notificationName的notification轉發給observer。

-(void)postNotification:(NSNotification *)notification

上面的函數發送notification至通告中心。

創建併發送一個notification可以用下面的代碼:

-(void)postNotificationName:(NSString * name)aName
Object:(id)anObject

移除observer:

-(void)removeObserver:(id)observer

下面是發送一個通告的示例代碼:

//創建通告名字
NSString *myNotificationName=@"myNotification";
//獲取通告中心
NSNotificationCenter *nc=[NSNotificationCenter defaultCenter];
//發送通告
[nc PostNotificationName :myNotificationName object:self];

要註冊一個observer,必須提供幾個參數:要成爲observer的對象、所感興趣的notification的名字以及當notification發送時要調用的方法,也可以指定關注某個對象的notification。

-(id)int{
Self =[super inti];
If(self!=nil){
NSNotificationCenter *center=[NotificationCenter defaultCenter];
[ nc addObserver:self Selector:@seletor(actionFunc:)Name:myNotificationName Object:nil]
}
return self;
}

在delloc中將移除observer對象可以使用以下代碼:

-(void)dealloc{
NSNotificationCenter *nc=[NSNotificationCenter defaultCenter];
[nc removeObserver:self];
[super dealloc];
}
當notification發生時,處理actionFunc函數:

-(void)actionFunc:(NSNotification * )note{
  NSlog(@"Received notification:%@",note);
}
notification對象的object變量時post而,如果我們想要notification對象傳遞更多的信息,我們可以使用user info dictionary。每個notification對象有一個變量叫userinfo,它是一個NSDiticitonary 對象,用來存放用戶希望隨着notification一起傳遞到observer的其他信息。

下面修改通告發送代碼:

//創建通告的名字
NSSting * myNotificationName=@"myNotification";
//創建通告中心
NSNotificationCenter *nc=[NSNotificationCenter defaultCenter];
//創建參數子彈
NSDictionary *d=[NSDictionary dictionaryWithObject:@"object"forKey:@"key"];
//發送通告
[nc PostNotificationName :myNotificationName object:self userInfo:d];
//修改actionFun方法
-(void)actionFun:(NSNotification *note){
  NSlog(@"Recevied notification :%@",note);
NSLog(@"Recevied notification param:%@",[[note userInfo]objectForKey:@ey]);
}






發佈了33 篇原創文章 · 獲贊 6 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章