您的位置:首页 > 产品设计 > UI/UE

UIday2202:IOS设计模式:通知中心

2015-09-23 22:42 435 查看
IOS设计模式:通知中心

1 什么是通知中心

2 怎么创建通知中心

3 怎么发送通知中心

4 怎么接收通知中心

消息的发送

/*

//创建消息:
NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];

//消息类型:
@interface NSNotification : NSObject <NSCopying, NSCoding>
@property (readonly, copy) NSString *name; //消息名字,相当于频段
@property (readonly, retain) id object;  //消息对象
@property (readonly, copy) NSDictionary *userInfo;  //通知内容

//发送消息
[notificationCenter postNotificationName:@"BJBroadcase" object:self userInfo:dict];

//接收消息
// 1 注册 2 接收
-(void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;

*/

// 北京广播电台  BJBroadcase
// 听众  Listener

//要循环发送的话要做一个定时器
-(void)broadcaseLooper{
//每一秒发一个
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(broadcast) userInfo:nil repeats:YES];
//启动一个定时器  循环的发送广播
}
//这个发送会随定时器循环发送
-(void)broadcast{
//1 取得通知中心(通知中心的创建)是一个类方法
NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
//count 做计数  i做计数器
static int i;
NSString * count = [NSString stringWithFormat:@"bcast %d",i++];
NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:@"BJ broadcase",@"name", count,@"Value",nil];
//消息内容
//2 发送广播
[nc postNotificationName:@"BJBroadcase" object:self userInfo:dict];
//param1 广播的频段 表示发送方和接收方要对应一致

}


消息的接收

-(void)wantToListen{
//1 要注册
//前两个参数是只要有BJBroadcast广播就调用self的recvBcaset:方法
//第三个参数是广播的名字 对应和 发送的名字一致
//第四个参数一般都是nil 设成具体的参数就相当于具体广播站
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(recvBcast:) name:@"BJBroadcase" object:nil];

}

//2 要真正的接收广播数据
-(void)recvBcast:(NSNotification *)notify{
//notify 就是具体的广播消息
NSString * name = notify.name;
NSLog(@"notify is %@",name);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: