首页 > 代码库 > OC-消息通知
OC-消息通知
/******************beijing*************************/
beijing.h
#import <Foundation/Foundation.h>
@interface beijing : NSObject
{
NSString *_name;
NSInteger _time;
}
@property(nonatomic)NSString *name;
@property(nonatomic)NSInteger time;
-(id)initWithName:(NSString *)newName andTime:(NSInteger)newTime;
-(void)broadcastloop;
-(void)broadcast;
@end
#import "beijing.h"
int i = 0;
@implementation beijing
-(id)initWithName:(NSString *)newName andTime:(NSInteger)newTime{
_name = newName;
_time = newTime;
return self;
}
//重复发送
-(void)broadcastloop{
//定时器
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(broadcast) userInfo:nil repeats:YES];
//循环发广播
}
//一次广播:
-(void)broadcast{
//获得通知中心
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
//广播内容为字典
NSString *count = [NSString stringWithFormat:@"%i",i++];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"beijing",@"name",count,@"value",nil];
//发送广播
//参数解释:
//第一个是广播的名字"beijing",在接收端就是以这个名字来监听接收的,
//第二个是要传过去的对象"self",如果你用,就传,不用就设置为“nil”,
//第三个是传过去的信息"dict",这个信息是封装在字典里面的数据。
[nc postNotificationName:@"beijing" object:self userInfo:dict];
//频段,发送者,内容
}
@end
/******************Listener*************************/
Listener.h
#import <Foundation/Foundation.h>
@interface Listener : NSObject
-(void)wanttolisten;
-(void)recvbroadcast:(NSNotification *)notify;
@end
#import "Listener.h"
@implementation Listener
-(void)wanttolisten{
//注册广播,监听,把监听到的广播对象:“NSNotification *”作为参数传入函数:“recvbroadcast:”里面进行进一步的处理。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recvbroadcast:) name:@"beijing" object:nil];
/*参数一指定使用参数为的对象,【self receive:】;
参数二指定接收方法
参数三指定接收的频段
参数四,指定接收的对象,没有就以频段为主,
*/
}
-(void)recvbroadcast:(NSNotification *)notify{
//notify是具体的广播消息,
NSLog(@"%@",notify);
/*
提取广播的名称:
- (NSString *)name;
提取广播传来的对象:
- (id)object;
提取广播传来的字典:
- (NSDictionary *)userInfo;
*/
id obj = [notify object];
[obj me];
NSLog(@"广播的名称:%@",[notify name]);
NSDictionary *dict = [notify userInfo];
NSLog(@"传过来的字典的内容是:%@",dict);
for (id obj in dict) {
NSLog(@"%@",obj);
}
}
@end
#import <Foundation/Foundation.h>
#import "beijing.h"
#import "Listener.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
//观众需要先收听,如果广播只发送一次。
beijing *bei = [[beijing alloc] init];
[bei broadcastloop];
Listener *listener = [[Listener alloc] init];
[listener wanttolisten];
//发送这一个广播同时有两个人在监听。
Listener *listener1 = [[Listener alloc] init];
[listener1 wanttolisten];
//防止计数器停止。
[[NSRunLoop currentRunLoop] run];
}
return 0;
}
OC-消息通知