測試iOS的Notification是同步還是非同步

來源:互聯網
上載者:User

標籤:ESS   UI   ica   通過   inf   nsstring   tno   orm   action   

面試被問到這個問題,不是很清楚,寫代碼測試並記錄一下。

#pragma mark - 測試通知
-(void)testNotification
{
    // 初始化一個按鈕
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
    button.backgroundColor = [UIColor orangeColor];
    [button setTitle:@"觸發通知" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonDown) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    // 註冊通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(actionNotification:)
                                                 name:kNotificationName
                                               object:nil];
}
- (void) actionNotification: (NSNotification*)notification
{
    NSString* message = notification.object;
    NSLog(@"message:%@",message);
    
    sleep(3);   // 睡3秒
    NSLog(@"通知說話結束");
}

- (void)buttonDown
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"通知說話開始"];
    NSLog(@"按鈕說話");
}

點擊觸發通知按鈕後,控制台列印如下:

通過這裡的時間間隔可以看出,通知的過程是同步進行的。

在拋出通知以後,觀察者在通知事件處理完成以後(這裡我們休眠3秒),拋出者才會往下繼續執行,也就是說這個過程預設是同步的;當發送通知時,通知中樞會一直等待所有的observer都收到並且處理了通知才會返回到poster;

PS:

如果想改同步為非同步,也是有辦法的。比如讓通知事件處理方法在子線程中執行。

- (void) actionNotification: (NSNotification*)notification
{
//    NSString* message = notification.object;
//    NSLog(@"message:%@",message);
//
//    sleep(3);   // 睡3秒
//    NSLog(@"通知說話結束");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString* message = notification.object;
        NSLog(@"message:%@",message);
        
        sleep(3);
        
        NSLog(@"通知說話結束:%@",[NSThread currentThread]);
        
    });
}

- (void)buttonDown
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"通知說話開始"];
    NSLog(@"按鈕說話:%@",[NSThread currentThread]);
}

此時點擊觸發通知按鈕,控制台列印輸入:

 

測試iOS的Notification是同步還是非同步

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.