在使用通知中心进行传值,接收界面必须先监听。这是在编写程序时容易被忽略的,而且不容易发现错误。现在通过一段代码进行详细解释。
有两个界面,第一个界面有一个UIButton控件,点击UIButton,将第值传给第二个界面:
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
_firstController = [[FirstViewController alloc]init];
_secondController = [[SecondViewController alloc]init];
//在启动应用程序时,为了节省内存,第二个页面并没有加载,此时,第二个页面并没有做监听,所以第二个页面接受不到数据。所以我们可以给其加个颜色让程序启动时,第二个页面做监听
_secondController.view.backgroundColor = [UIColor redColor];//修改代码
或者做如下改动:
//@selector 可以跨类寻找方法,但在第二界面的.h文件中要进行定义
[[NSNotificationCenter defaultCenter]addObserver:__secondController selector:@selector(notifiListen:)name:@"Msg" object:nil];
self.window.rootViewController = _firstController;
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
FirsrtViewController.m中:
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
btn.frame = CGRectMake(100, 100, 100, 30);
btn.backgroundColor = [UIColor grayColor];
[btn setTitle:@"NSNOtifition" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
//给UIButton添加点击事件
-(void)btnClick:(UIButton*)bt
{ NSArray *array = @[@"a",@"b"];
//通过通知中心想外发送一包数据 第一个随便给参数,第二个传得参数
[[NSNotificationCenter defaultCenter]postNotificationName:@"Msg" object:array];
}
-(void)notifitionListen:(NSNotification*)notifi;
- (void)viewDidLoad
{
[super viewDidLoad];
// [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notifiListen:) name:@"Msg" object:nil];
}
-(void)notifiListen:(NSNotification*)n{
//解析传递的数据
NSLog(@"%@",[n object]);
}