標籤: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是同步還是非同步