这是我在 千峰视频网上看到的 对于学习通知的例子还是挺有用的。
一、首先创建一个简单的命令行工程
//
// BJBroadcast.m
// 通知中心
//
// Created by qin on 14-4-29.
// Copyright (c) 2014年 zhou. All rights reserved.
//
//通知中心代码
#import "BJBroadcast.h"
@implementation BJBroadcast
- (void)broadvastLooper
{
[NSTimer
scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(broadcast)
userInfo:nil
repeats:YES];
}
- (void)broadcast
{
//1.取得通知中心
NSNotificationCenter *nc = [NSNotificationCenter
defaultCenter];
static
int i;
NSString *count = [NSString
stringWithFormat:@"bcast %d",i++];
NSDictionary *dict = [NSDictionary
dictionaryWithObjectsAndKeys:@"BJ broadcast",@"name",count,@"Value",
nil];
//2.发送广播
[nc postNotificationName:@"BJBroadcast"
object:self
userInfo:dict];
}
@end
//接收方代码
#import "Listener.h"
@implementation Listener
- (void)wantToListen
{
[[NSNotificationCenter
defaultCenter]addObserver:self
selector:@selector(recvBcast:)
name:@"BJBroadcast"
object:nil];
//param1 param2
这两个参数是只要有BJBroadcast广播就调用[self recvBcast]
//第四个蚕食一般都设为nil
//要真正的接收广播数据
}
- (void)recvBcast:(NSNotification *)notify
{
// NSString *name = notify.name;
NSLog(@"notiy is %@",notify);
}
@end
主函数:
#import <Foundation/Foundation.h>
#import "BJBroadcast.h"
#import "Listener.h"
int main(int argc,
const char * argv[])
{
@autoreleasepool
{
Listener *l1 = [[Listener
alloc]init];
[l1
wantToListen]; //监听者
BJBroadcast *bj = [[BJBroadcast
alloc]init];
[bj
broadcast]; //通知者
[[NSRunLoop
currentRunLoop]run];
}
return 0;
}
打印:
2014-04-29 23:41:21.131
通知[760:303] notiy is NSConcreteNotification 0x10010c790 {name = BJBroadcast; object = <BJBroadcast: 0x10010c200>; userInfo = {
Value = "bcast 0";
name = "BJ broadcast";
}}
主要的代码 就是发送广播和接收广播
[nc postNotificationName:@"BJBroadcast"
object:self
userInfo:dict];
[[NSNotificationCenter
defaultCenter]addObserver:self
selector:@selector(recvBcast:)
name:@"BJBroadcast"
object:nil];
开发中经常会用到通知....