1. 程式人生 > >Notification 到底怎麽玩 ?

Notification 到底怎麽玩 ?

\n pre nonnull nss lec 怎麽 not ons void

請一定註意log中打印時間 & 線程

主線程註冊通知

- (instancetype)init {
    
    self = [super init];
    if (self) {
        
        [self addNotifications];
    }
    return self;
}

- (void)addNotifications {
    
    NSLog(@"\n 註冊 通知  ----- %@ ", [NSThread currentThread]);
    
    __weak typeof(self) weakSelf = self;
    
/* queue: 決定接收通知的線程 nil-與發通知的線程一致, currentQueue-與註冊通知的線程一致, mainQueue-在主線程 usingBlock: 在規定的線程回調收到的通知 */ [[NSNotificationCenter defaultCenter] addObserverForName:kNotificationName1 object:nil queue:nil usingBlock:
^(NSNotification * _Nonnull note) { [weakSelf receviedNotificaion1:note]; }]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receviedNotificaion2:) name:kNotificationName2
object:nil]; } - (void)receviedNotificaion1:(NSNotification *)note { sleep(1.0); NSLog(@"\n 收到 通知1 數據 ----- %@ ", [NSThread currentThread]); } - (void)receviedNotificaion2:(NSNotification *)note { sleep(2.0); NSLog(@"\n 收到 通知2 數據 ----- %@ ", [NSThread currentThread]); }

串行、並行、主隊列分別發送通知

  dispatch_queue_t queue ;
    NSString *pushMethod = @"";
    if (button.tag == 100) {
       
        pushMethod = @"串行隊列";
        queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_SERIAL);
    
    } else if (button.tag == 200) {
    
        pushMethod = @"並行隊列";
        queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_CONCURRENT);
   
    } else if (button.tag == 300) {
       
        pushMethod = @"主隊列";
        queue = dispatch_get_main_queue();
    }
    
    dispatch_async(queue, ^{
        // 追加任務1
        for (int i = 0; i < 2; ++i) {

            NSLog(@"\n %@ 發出 通知1 數據 ----- %@ ",pushMethod, [NSThread currentThread]);
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName1
                                                                object:nil
                                                              userInfo:@{@"index":@(i+200)}];
            NSLog(@"\n %@ 結束 通知1  ----- %@ ", pushMethod, [NSThread currentThread]);
        }
    });
    
    dispatch_async(queue, ^{
        
        for (int i = 0; i < 2; i++) {
            
            NSLog(@"\n %@ 發出 通知2 數據 ----- %@ ",pushMethod, [NSThread currentThread]);
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName2
                                                                object:nil
                                                              userInfo:@{@"index":@(i+100)}];
            NSLog(@"\n %@ 結束 通知2  ----- %@ ",pushMethod, [NSThread currentThread]);
        }
    });

控制臺打印結果如下

1.串行發通知,睡眠1s後,收到通知log才打印。這 1s 模擬某種場景,然後繼續發通知後續代碼,但是不會卡主線程

2.並行隊列發通知,睡眠1s後,收到通知log才打印。

3.主隊列發通知,睡眠1s後,收到通知log才打印。

Notification 到底怎麽玩 ?