//通知中心广播站建立
//1.head.h
#import <Foundation/Foundation.h>
@interface BJBroadcast : NSObject
-(void)sendBroadCast;
-(void)sendBroadCastLoop;
@end
//2.implementation
#import "BJBroadcast.h"
@implementation BJBroadcast
-(void)sendBroadCastLoop
{
//每隔一秒发送一次广播消息
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(sendBroadCast) userInfo:nil repeats:YES];
}
-(void)sendBroadCast
{
//创建广播站
NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter];
static NSUInteger i;
NSString *count=[[NSString alloc]initWithFormat:@"broadCount %ld",i++];
NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:@"BJBroadcast",@"Name",count,@"Timer", nil];
[notificationCenter postNotificationName:@"BJBroadcast" object:self userInfo:dic];
[count release];
[dic release];
}
@end
//广播接受者
//1.head.h
@interface Listener : NSObject
-(void)wantTolistenBroadcast;
@end
//implementation
#import "Listener.h"
@implementation Listener
-(void)wantTolistenBroadcast
{
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(Broadcast:) name:@"BJBroadcast" object:nil];
/*#program mark
1.addObserver:表示谁对通知中心发出的信息感兴趣
2.selector:收到该感兴趣信息的处理函数
3.name:对什么名字的广播感兴趣
4.object:对谁发出的广播感兴趣,nil表示对任何人发出的广播都感兴趣
*/
}
-(void)Broadcast:(NSNotification *)notification
{
NSLog(@"%@",notification);
}
@end
//main
#import <Foundation/Foundation.h>
#import "BJBroadcast.h"
#import "Listener.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Listener *aListener=[[Listener alloc]init];
[aListener wantTolistenBroadcast];
BJBroadcast *Bj=[[BJBroadcast alloc]init];
[Bj sendBroadCastLoop];
[[NSRunLoop currentRunLoop] run];//一定要添加该方法,否则无法循环
[aListener release];
[Bj release];
}
return 0;
}
转载于:https://blog.51cto.com/8947509/1555031