NSNotificationCenter 通知中心实现传值
来源:互联网 发布:淘宝上买圣衣神话 编辑:程序博客网 时间:2024/06/11 14:20
在使用通知中心进行传值,接收界面必须先监听。这是在编写程序时容易被忽略的,而且不容易发现错误。现在通过一段代码进行详细解释。
有两个界面,第一个界面有一个UIButton控件,点击UIButton,将第值传给第二个界面:
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]];
_firstController = [[FirstViewControlleralloc]init];
_secondController = [[SecondViewControlleralloc]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.windowmakeKeyAndVisible];
returnYES;
}
FirsrtViewController.m中:
- (void)viewDidLoad
{
[superviewDidLoad];
UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeSystem];
btn.frame =CGRectMake(100,100, 100, 30);
btn.backgroundColor = [UIColorgrayColor];
[btn setTitle:@"NSNOtifition"forState:UIControlStateNormal];
[btn addTarget:selfaction:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:btn];
}
//给UIButton添加点击事件
-(void)btnClick:(UIButton*)bt
{ NSArray *array =@[@"a",@"b"];
//通过通知中心想外发送一包数据 第一个随便给参数,第二个传得参数
[[NSNotificationCenterdefaultCenter]postNotificationName:@"Msg"object:array];
}
-(void)notifitionListen:(NSNotification*)notifi;
- (void)viewDidLoad
{
[superviewDidLoad];
// [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(notifiListen:)name:@"Msg"object:nil];
}
-(void)notifiListen:(NSNotification*)n{
//解析传递的数据
NSLog(@"%@",[nobject]);
}
- NSNotificationCenter 通知中心实现传值
- 协议代理Delegate与通知中心NSNotificationCenter实现页面传值
- IOS NSNotificationCenter(通知中心)实现原理
- 通知中心NSNotificationCenter
- 通知中心 NSNotificationCenter
- IOS NSNotificationCenter 通知中心
- 通知中心(NSNotificationCenter)
- NSNotificationCenter 通知中心
- 通知中心NSNotificationCenter
- NSNotificationCenter通知中心
- IOS NSNotificationCenter 通知中心
- NSNotificationCenter通知中心
- iOS通知中心(NSNotificationCenter)
- NSNotificationCenter(通知中心)
- 通知中心NSnotificationCenter
- iOS通知中心NSNotificationCenter
- 通知中心(NSNotificationCenter)
- 通知中心(NSNotificationCenter)
- php通过pdo连接mssql
- hdu 5122 K.Bro Sorting
- Spring MVC 中 HandlerInterceptorAdapter的使用
- Java对Map排序
- LeetCode-Linked List Cycle II
- NSNotificationCenter 通知中心实现传值
- [二分]poj3104 Drying
- 2015 Multi-University Training Contest 4(HDOJ5327、5328、5335、5536)
- 机试算法讲解: 第55题 完全背包之储蓄罐最少放了多少钱
- ICCMO微信公众账号开发系列(2)打造微信聊天机器人
- noip知识范围
- 二叉树的最大深度
- 无向图的割顶和桥(tarjan模板)
- Vijos1128.选数