您好,登錄后才能下訂單哦!
1、獲得通知中心對象
NSNotificationCenter *center= [NSNotificationCenter defaultCenter]; //單例實際事獲得通知中心的地址
2、監聽通知
[center addObserver :監聽者 selector:須執行的方法 name:所監聽者通知的名稱 object:通知發送者];
3、通知中心發布消息
[center PostNotificationName:@"為人民服務" object:某人];
4.移除監聽中心
[center removeObserver:self name:@"為人民服務" object:某人];
創建King、Worker、Farmer類,由King發一個自定義通知,Worker和Farmer類監聽通知,通知內容為打印“某某為人民服務”。
#import <Foundation/Foundation.h>
@interface King : NSObject
-(void)senfMessage;//創建并發送通知
@end
#import "King.h"
@implementation King
-(void)senfMessage{
//創建通知對象,通知的名字是MESSAGE
NSNotification *notification = nil;
notification = [NSNotificationnotificationWithName:@"MESSAGE"object:selfuserInfo:nil];
//發送通知
[[NSNotificationCenterdefaultCenter] postNotification:notification];
NSLog(@"我是國王,我正在給我的子民發送通知");
}
@end
#import <Foundation/Foundation.h>
@interface Worker : NSObject
@property(retain,nonatomic) NSString *name;
-(void)say:(NSNotification *) notif;//收到通知后要做的事
@end
#import "Worker.h"
@implementation Worker
-(id)init{
if (self = [superinit]) {
//注冊監聽者
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(say:) name:@"MESSAGE"object:nil];
}
returnself;
}
-(void)say:(NSNotification *) notif{//收到通知后要做的事
Worker *wk = [[Workeralloc] init];
wk.name = @"小麥";
NSLog(@"工人%@說我要為人民服務",wk.name);
[wk release];
}
-(void)dealloc{//移除通知
[[NSNotificationCenterdefaultCenter] removeObserver:selfname:@"MESSAGE"object:nil];
[superdealloc];
}
@end
#import <Foundation/Foundation.h>
@interface Farmer : NSObject
@property(retain,nonatomic) NSString *name;
-(void)say:(NSNotification *) notif;//收到通知后要做的事
@end
#import "Farmer.h"
@implementation Farmer
-(id)init{
if (self = [superinit]) {
//注冊監聽者
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(say:) name:@"MESSAGE"object:nil];
}
returnself;
}
-(void)say:(NSNotification *) notif{//收到通知后要做的事
Farmer *fa = [[Farmeralloc] init];
fa.name = @"小明";
NSLog(@"農民%@說我要為人民服務",fa.name);
[fa release];
}
-(void)dealloc{//移除通知
[[NSNotificationCenterdefaultCenter] removeObserver:selfname:@"MESSAGE"object:nil];
[superdealloc];
}
@end
#import <Foundation/Foundation.h>
#import "King.h"
#import "Worker.h"
#import "Farmer.h"
int main(int argc, constchar * argv[])
{
@autoreleasepool {
//對象初始化
Worker *w = [[Workeralloc]init];
Farmer *f = [[Farmeralloc]init];
King *k = [[Kingalloc]init];
[k senfMessage];//創建并發送通知
[k release];
[w release];
[f release];
}
return 0;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。