iOS 通知原理解析

  • 通知的概念

一些基本的概念就不做介绍了,应该都明白,好了,直接上代码
为了方便查看,发送通知和接受通知就放在同一个文件里,一般项目不会这么用,但是操作都是一样的
可以po一下 [[NSNotificationCenter defaultCenter],你会发现其实就是个列表,包含了系统通知,用户通知等

- (void)viewDidLoad {
    [super viewDidLoad];
    //object:指定接受某个对象的通知,为nil表示可以接受任意对象的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifi:) name:@"EdisonNotif" object:nil];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self sendNotification];
}


-(void)sendNotification{

    NSLog(@"发送通知before:%@",[NSThread currentThread]);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"EdisonNotif" object:nil];
    NSLog(@"发送通知after:%@",[NSThread currentThread]);
}


-(void)handleNotifi:(NSNotification*)notif{

    
    NSLog(@"接收到通知了:%@",[NSThread currentThread]);
}

打印结果:
/*
 2017-08-30 14:48:58.916 通知的底层解析[1422:94722] 发送通知before:<NSThread: 0x600000063500>{number = 1, name = main}
 2017-08-30 14:48:58.916 通知的底层解析[1422:94722] 接收到通知了:<NSThread: 0x600000063500>{number = 1, name = main}
 2017-08-30 14:48:58.917 通知的底层解析[1422:94722] 发送通知after:<NSThread: 0x600000063500>{number = 1, name = main}
 */

以上代码就是我们平时所写的发送注册通知了一般写法,点击屏幕发送一次通知,看清楚打印顺序,before->处理通知->after
这说明了是消息发完之后要等处理了消息才跑发送消息之后的代码,这跟多线程中的同步概念相似,所以在同步的通知的方法里不要做耗时的操作,要不然就阻塞主线程

  • 使用(同步,异步)

上面介绍了同步,那么我们来说说异步的,就是我发送完之后就继续跑下面的代码,不需要去管接受通知的处理
比如异步,那么就要用到通知对列

//同步
-(void)sendNotification{

   //每个线程都默认又一个通知队列,可以直接获取,也可以alloc
    NSNotificationQueue * notificationQueue = [NSNotificationQueue defaultQueue];
    
    NSNotification * notification = [NSNotification notificationWithName:@"EdisonNotif" object:nil];
    //NSNotification * notificationTwo = [NSNotification notificationWithName:@"EdisonNotif" object:nil];
 
/*
     (NSPostingStyle) 什么时候发送
     NSPostWhenIdle = 1,//空闲时发送
     NSPostASAP = 2,//尽快发送
     NSPostNow = 3,//现在发送
     
     
     <#(NSNotificationCoalescing)#>消息合并的方式
     NSNotificationNoCoalescing = 0, //不合并
     NSNotificationCoalescingOnName = 1,//按名称合并
     NSNotificationCoalescingOnSender = 2,//按发送者合并
     
     */
    NSLog(@"异步发送通知before:%@",[NSThread currentThread]);
    [notificationQueue enqueueNotification:notification postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];
    //[notificationQueue enqueueNotification:notificationTwo postingStyle:NSPostNow coalesceMask:NSNotificationCoalescingOnName forModes:nil];
    //[notificationQueue enqueueNotification:notification postingStyle:NSPostNow coalesceMask:NSNotificationCoalescingOnName forModes:nil];
    NSLog(@"异步发送通知after:%@",[NSThread currentThread]);
    
    /*
     2017-08-30 15:43:13.068 通知的底层解析[4206:132048] 异步发送通知before:<NSThread: 0x60000007e180>{number = 1, name = main}
     2017-08-30 15:43:13.068 通知的底层解析[4206:132048] 异步发送通知after:<NSThread: 0x60000007e180>{number = 1, name = main}
     2017-08-30 15:43:13.069 通知的底层解析[4206:132048] 接收到通知了:<NSThread: 0x60000007e180>{number = 1, name = main}
     */
}

如果把发送通知的方法sendNotification改成如上,打印的结果就是表明是异步发送了

再看下通知队列跟线程的了关系,把点击屏幕直接发送通知,改成开启一个线程发送通知

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [NSThread detachNewThreadSelector:@selector(sendAsyncNotification) toTarget:self withObject:nil];
    /*
     2017-08-30 15:51:17.254 通知的底层解析[4244:137397] 异步发送通知before:<NSThread: 0x600000079480>{number = 3, name = (null)}
     2017-08-30 15:51:17.255 通知的底层解析[4244:137397] 异步发送通知after:<NSThread: 0x600000079480>{number = 3, name = (null)}
     */
}

看打印结果,发现根本没有处理通知
再改下代码,用线程发送同步的通知中心

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    //[self sendNotification];
    
    [NSThread detachNewThreadSelector:@selector(sendNotification) toTarget:self withObject:nil];
    //[self sendAsyncNotification];
    
}
/*
2017-08-30 15:54:49.932 通知的底层解析[4263:139861] 发送通知before:<NSThread: 0x60000026bc40>{number = 3, name = (null)}
2017-08-30 15:54:49.933 通知的底层解析[4263:139861] 接收到通知了:<NSThread: 0x60000026bc40>{number = 3, name = (null)}
2017-08-30 15:54:49.933 通知的底层解析[4263:139861] 发送通知after:<NSThread: 0x60000026bc40>{number = 3, name = (null)}
*/

而用线程发送同步的是可以接受到通知的,并且处理也是在线程里处理的
,这说通知队列跟线程是有关系的,再继续改代码,回到线程发送异步通知,只是把发送时机改成马上发送

[notificationQueue enqueueNotification:notification postingStyle:NSPostNow coalesceMask:NSNotificationNoCoalescing forModes:nil];
/*
2017-08-30 15:59:19.426 通知的底层解析[4276:143034] 异步发送通知before:<NSThread: 0x60800006a180>{number = 3, name = (null)}
2017-08-30 15:59:19.426 通知的底层解析[4276:143034] 接收到通知了:<NSThread: 0x60800006a180>{number = 3, name = (null)}
2017-08-30 15:59:19.426 通知的底层解析[4276:143034] 异步发送通知after:<NSThread: 0x60800006a180>{number = 3, name = (null)}
*/

这又能处理通知,所以可以说NSPostNow就是同步,其实呢,[[NSNotificationCenter defaultCenter]通知中心这句代码的意思就是:你在哪个线程里面就是获取当前线程的通知队列并且默认采用NSPostNow发送时机

 NSLog(@"异步发送通知before:%@",[NSThread currentThread]);
    [notificationQueue enqueueNotification:notification postingStyle:NSPostWhenIdle coalesceMask:NSNotificationNoCoalescing forModes:nil];
    NSLog(@"异步发送通知after:%@",[NSThread currentThread]);

那么通知队列到底和线程有什么关系呢:每个线程都有一个通知队列,当线程结束了,通知队列就被释放了,所以当前选择发送时机为NSPostWhenIdle时也就是空闲的时候发送通知,通知队列就已经释放了,所以通知发送不出去了
如果线程不结束,就可以发送通知了,用runloop让线程不结束

//异步
-(void)sendAsyncNotification{

    //每个线程都默认又一个通知队列,可以直接获取,也可以alloc
    NSNotificationQueue * notificationQueue = [NSNotificationQueue defaultQueue];
    
    NSNotification * notification = [NSNotification notificationWithName:@"EdisonNotif" object:nil];
    
   
    NSLog(@"异步发送通知before:%@",[NSThread currentThread]);
    [notificationQueue enqueueNotification:notification postingStyle:NSPostWhenIdle coalesceMask:NSNotificationNoCoalescing forModes:nil];
    NSLog(@"异步发送通知after:%@",[NSThread currentThread]);
    
    NSPort * port = [NSPort new];
    [[NSRunLoop currentRunLoop] addPort:port forMode:NSRunLoopCommonModes];
    
    [[NSRunLoop currentRunLoop] run];
}
/*
2017-08-30 16:12:55.098 通知的底层解析[4394:153794] 异步发送通知before:<NSThread: 0x600000070200>{number = 3, name = (null)}
2017-08-30 16:12:55.098 通知的底层解析[4394:153794] 异步发送通知after:<NSThread: 0x600000070200>{number = 3, name = (null)}
2017-08-30 16:12:55.099 通知的底层解析[4394:153794] 接收到通知了:<NSThread: 0x600000070200>{number = 3, name = (null)}

*/

这样通知就被发送出去了,而且发送和处理也在线程中,这还没有达到真正的异步是吧,应该发送在一个线程,处理在另一个线程

再来看下消息合并

//异步
-(void)sendAsyncNotification{

    //每个线程都默认又一个通知队列,可以直接获取,也可以alloc
    NSNotificationQueue * notificationQueue = [NSNotificationQueue defaultQueue];
    
    NSNotification * notification = [NSNotification notificationWithName:@"EdisonNotif" object:nil];
    NSNotification * notificationtwo = [NSNotification notificationWithName:@"EdisonNotif" object:nil];
    
    /*
     <#(NSNotificationCoalescing)#>消息合并的方式
     NSNotificationNoCoalescing = 0, //不合并
     NSNotificationCoalescingOnName = 1,//按名称合并
     NSNotificationCoalescingOnSender = 2,//按发送者合并
     
     */
    NSLog(@"异步发送通知before:%@",[NSThread currentThread]);
    [notificationQueue enqueueNotification:notification postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];
    [notificationQueue enqueueNotification:notificationtwo postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];
    [notificationQueue enqueueNotification:notification postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];
    NSLog(@"异步发送通知after:%@",[NSThread currentThread]);
    
    NSPort * port = [NSPort new];
    [[NSRunLoop currentRunLoop] addPort:port forMode:NSRunLoopCommonModes];
    
    [[NSRunLoop currentRunLoop] run];
}

/*
2017-08-30 16:22:16.149 通知的底层解析[4407:159094] 异步发送通知before:<NSThread: 0x608000265640>{number = 8, name = (null)}
2017-08-30 16:22:16.154 通知的底层解析[4407:159094] 异步发送通知after:<NSThread: 0x608000265640>{number = 8, name = (null)}
2017-08-30 16:22:16.154 通知的底层解析[4407:159094] 接收到通知了:<NSThread: 0x608000265640>{number = 8, name = (null)}

*/

设置成NSNotificationCoalescingOnName按名称合并,此时我连续发送三条,但是只处理了一次,
再继续,上面代码就只是把发送时机改成NSPostNow

    [notificationQueue enqueueNotification:notification postingStyle:NSPostNow coalesceMask:NSNotificationCoalescingOnName forModes:nil];
    [notificationQueue enqueueNotification:notificationTwo postingStyle:NSPostNow coalesceMask:NSNotificationCoalescingOnName forModes:nil];
    [notificationQueue enqueueNotification:notification postingStyle:NSPostNow coalesceMask:NSNotificationCoalescingOnName forModes:nil];
/*
2017-08-30 16:30:04.114 通知的底层解析[4442:164620] 异步发送通知before:<NSThread: 0x600000269a40>{number = 3, name = (null)}
2017-08-30 16:30:04.115 通知的底层解析[4442:164620] 接收到通知了:<NSThread: 0x600000269a40>{number = 3, name = (null)}
2017-08-30 16:30:04.115 通知的底层解析[4442:164620] 接收到通知了:<NSThread: 0x600000269a40>{number = 3, name = (null)}
2017-08-30 16:30:04.115 通知的底层解析[4442:164620] 接收到通知了:<NSThread: 0x600000269a40>{number = 3, name = (null)}
2017-08-30 16:30:04.116 通知的底层解析[4442:164620] 异步发送通知after:<NSThread: 0x600000269a40>{number = 3, name = (null)}
*/

结果就打印了处理了三次通知,这个应该好理解吧,就跟dispatch_sync原理一样,就是得发送因为NSPostNow是同步的,所以发送第一条通知,得等处理完第一条通知,才跑发送第二条通知,这样肯定就没有合并消息一说了,因为这有点类似线程阻塞的意思,只有异步,就是三个发送通知全部跑完,在处理通知的时候看是否需要合并和怎么合并,再去处理

那么系统哪些消息是合并的

drawRect

  • 通知队列(线程关系,消息合并等,系统哪些消息做了合并)

  • 底层通信port(同线程处理,不同线程处理)

通知队列也可以实现异步,但是真正的异步还是得通过port

NSPort,底层所有的消息触发都是通过端口来进行操作的

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifi:) name:@"EdisonNotif" object:nil];
    
    _port  =[[NSPort alloc] init];
    //消息处理通过代理来处理的
    _port.delegate=self;
    //把端口加在哪个线程里,就在哪个线程进行处理,下面:加在当前线程的runloop里
    [[NSRunLoop currentRunLoop] addPort:_port forMode:NSRunLoopCommonModes];
    
}

//发送消息
-(void)sendPort{

    NSLog(@"port发送通知before:%@",[NSThread currentThread]);

    [_port sendBeforeDate:[NSDate date] msgid:1212 components:nil from:nil reserved:0];
 
    NSLog(@"port发送通知after:%@",[NSThread currentThread]);
}

//处理消息
- (void)handlePortMessage:(NSPortMessage *)message{

    
    NSLog(@"port处理任务:%@",[NSThread currentThread]);
    NSObject * messageObj = (NSObject*)message;
    NSLog(@"=%@",[messageObj valueForKey:@"msgid"]);
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    
    [self sendPort];
    
}
/*
2017-08-30 17:09:28.715 通知的底层解析[8171:198651] port发送通知before:<NSThread: 0x600000075440>{number = 1, name = main}
2017-08-30 17:09:28.715 通知的底层解析[8171:198651] port发送通知after:<NSThread: 0x600000075440>{number = 1, name = main}
2017-08-30 17:09:28.715 通知的底层解析[8171:198651] port处理任务:<NSThread: 0x600000075440>{number = 1, name = main}
2017-08-30 17:09:28.715 通知的底层解析[8171:198651] =1212
*/

这样显然全部都在一个线程里,修改下代码

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [NSThread detachNewThreadSelector:@selector(sendPort) toTarget:self withObject:nil];
  /*

*/
}
  • 分析层次结构(通知中心)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,458评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,454评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,171评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,062评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,440评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,661评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,906评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,609评论 0 200
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,379评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,600评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,085评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,409评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,072评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,088评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,860评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,704评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,608评论 2 270

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 一、多线程 说明下线程的状态 java中的线程一共有 5 种状态。 NEW:这种情况指的是,通过 New 关键字创...
    Java旅行者阅读 4,596评论 0 44
  • 冉姐写了思想碎片,我觉得这个方法好,其实日子就是这样,有时候是被打碎了,有时候是碎片居然组成了一副亮闪闪的画。我也...
    冠世墨玉yanzi阅读 282评论 3 4
  • 关于军训的那些事 提起参加军训这事,我想,大家心中应该都是一万个不愿意吧。其实,在参加我的第一次军训前,我也是这么...
    樂子阅读 383评论 0 2