iOS通知学习

学习通知提出的几个问题,
1、一般的通知方式(同步的)
2、如何定义异步通知
3、通知与线程的关系
4、如何在不同线程发送通知

1.1、通知的基本概念:自己百度呀。

[[NSNotificationCenter defaultCenter] postNotificationName:name object:nil userInfo:@{@"value":@"nihao"}]; //发送通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(print:) name:name object:nil]; // 接受通知

2.1 异步通知

NSNotification *noti = [NSNotification notificationWithName:name object:self];
NSNotificationQueue *queue = [[NSNotificationQueue alloc] init];
//    [queue enqueueNotification:noti postingStyle:NSPostWhenIdle];
[queue enqueueNotification:noti postingStyle:NSPostWhenIdle coalesceMask:NSNotificationNoCoalescing forModes:@[NSDefaultRunLoopMode]];
  • 注意: 每一个app只有一个 [NSNotificationCenter defaultCenter] 实例,而每一条线程都有一个 [[NSNotificationQueue alloc] init] 实例。

3、保证runloop运行,通知才能运行。一般上,在哪条线程发送通知,就在哪条线程接受通知。

- (IBAction)click:(id)sender {
    // 同步执行 系统默认开启了runloop
    [NSThread detachNewThreadWithBlock:^{
        NSLog(@"111");
        [[NSNotificationCenter defaultCenter] postNotificationName:name object:nil userInfo:@{@"value":@"nihao"}];
        NSLog(@"222");
    }];
    
    
//    // 异步执行 手动开启runLoop
    [NSThread detachNewThreadWithBlock:^{
        NSLog(@"111");
        NSNotification *noti = [NSNotification notificationWithName:name object:self];
        NSNotificationQueue *queue = [[NSNotificationQueue alloc] init];
        //    [queue enqueueNotification:noti postingStyle:NSPostWhenIdle];
        [queue enqueueNotification:noti postingStyle:NSPostWhenIdle coalesceMask:NSNotificationNoCoalescing forModes:@[NSDefaultRunLoopMode]];
        
        NSPort *prot = [NSPort port];
        [[NSRunLoop currentRunLoop] addPort:prot forMode:NSDefaultRunLoopMode];
        
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]]; // 自动释放线程
//        [[NSRunLoop currentRunLoop] run]; // 不会释放。
        NSLog(@"222");
    }];
    
}

NSNotificationCenter 系统处理了 runloop; NSNotificationCenter, NSNotificationQueue, NSPort,他们这三者的关系,是NSNotificationCenter 封装了NSNotificationQueue, NSNotificationQueue封装了NSPort

4、如何从子线程发送通知,主线程接受通知呢。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 先贴下 apple doc, 本文基本是对照 doc 的翻译:https://developer.apple.co...
    brownfeng阅读 6,981评论 8 111
  • 我们在开发程序的时候,程序内不同对象间的通信是不可避免的,iOS中主要有以下这些通信方式: 图中按照耦合度的强弱和...
    等开会阅读 8,287评论 9 48
  • iOS Foundation 框架简介(上) 接iOS Foundation 框架简介(上)的内继续介绍Found...
    zysmoon阅读 1,782评论 1 6
  • 五十岁以后的父亲总是提起往事,常把几天前刚刚讲过的事情重又提起,翻来覆去,乐此不疲,我不胜其烦。 去年的一个仲夏夜...
    张朋亮阅读 577评论 0 49
  • 鳗鱼饭,煎饺没拍上 晚水果:酸奶,柚子 参考目标: 1份肉2份豆制品3份“新鲜”水果4份谷物/薯5份蔬菜,深绿色叶...
    静趣_儿童心理师阅读 248评论 0 0