码迷,mamicode.com
首页 > 移动开发 > 详细

iOS的通知Notification

时间:2016-07-05 13:52:08      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

这里是不同的对象之间的通知, 不是本地通知.

 

一开始玩, 很挠头, 后来发现原来只是对象init的过程出了问题.

首先, 新建一个简单的单controller的工程.

然后打开它的ViewController.m文件

@interface ViewController ()
@property  NotifyObserver *obj;    //这里是关键, 应该有一个property是另一个要通知的类的, 我之前写在了viewDidLoad里面, 结果死活通知没有响应, 其实原因是这个对象在viewDidLoad方法完成后就自动销毁了, 还通知个屁.

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   self.obj=[[NotifyObserver alloc] init]; //这里init了一个要通知的对象.

    //NotifyObserver *obj=[[NotifyObserver alloc] init]; 之前是这么写的, 折腾了两个小时, 应该抽自己....
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)notifyButtonPressed:(id)sender {
    NSLog(@"pressed");
    //这里开始通知了, 还留下一个问题是如何拿到userInfo, 先不管, 总之发送了一个名为updateMessage的通知, 内容就是my object.
    NSNotification *notification = [[NSNotification alloc] initWithName:@"updateMessage" object:@"my object" userInfo:@{@"Status": @"Success"}];

    [[NSNotificationCenter defaultCenter] postNotification:notification];

}

@end

谁要接收这个通知, 就要去注册一下

@implementation NotifyObserver

-(id)init{
    NSLog(@"init"); 

    //在init方法里面注册自己是一个观察者, 然后定义自己只接收"updateMessage"的通知, 别乱七八糟的啥都通知我, 另外, 如果通知到了, 麻烦运行update方法, 记得后面有个":"意思是自己是带形参的方法, Java母语的人笑而不语
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(update:) name:@"updateMessage" object:nil];   
    return self;
}
-(void)dealloc{
   //记得这个对象要被销毁时, 要移除注册
   [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//这个update方法就是通知的回调, 一旦通知来了, 就麻烦运行这个方法.
-(void) update :(NSNotification *)notification
{
    NSLog(@"update");
    NSString* str = (NSString*)[notification object];//这里取出刚刚从过来的字符串
    NSLog(@"%@",str);
}

@end

几乎一天时间学会通知Notification, 够慢的....

越来越觉得iOS就是简单啊.....

通知, 委托, 这两个设计模式iOS玩得溜啊...

 

iOS的通知Notification

标签:

原文地址:http://www.cnblogs.com/Montauk/p/5643213.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!