温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

自定义通知

发布时间:2020-04-10 00:26:13 来源:网络 阅读:285 作者:江城子Dj 栏目:开发技术

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;

}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI