NSNotificationCenterの同期と非同期

2858 ワード

まず、コードを入力します.
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:CGRectMake(0, 0, 400, 60)];
    [button addTarget:self action:@selector(buttonDown) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Post Notification" forState:UIControlStateNormal];
    [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);
    
    sleep(5);
    
    NSLog(@"Action Notification Finish");
    
}

- (void)buttonDown
{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"object"];
    
    NSLog(@"buttonDown");
    
}

buttonをクリックすると、次のように印刷されます.
2015-03-17 17:17:59.285 AppTest[16470:169797] object
2015-03-17 17:18:04.285 AppTest[16470:169797] Action Notification Finish
2015-03-17 17:18:04.286 AppTest[16470:169797] buttonDown
ここでの時間間隔から、通知が投げ出された後、観察者は通知イベントの処理が完了した後(ここでは5秒休眠)、投げ出された者が下に実行を継続することが明らかになった.すなわち、このプロセスはデフォルトで同期されている.通知を送信すると、通知センターはすべてのobserverが受信し、通知がposterに戻るのを待っています.
非同期処理:
方法1:
通知イベント処理方法をサブスレッドで実行します.たとえば、次のようにします.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        sleep(5);
        
    });

ブロックは起こりません
方法2:NSNotificationQueueenqueueNotification:postingStyle:メソッドとenqueueNotification:postingStyle:coalesceMask:forModes:メソッドで通知をキューに入れ、非同期送信を実現できます.通知をキューに入れた後、これらのメソッドはすぐに呼び出しオブジェクトに制御権を返します.
buttonイベントを変更するには、次のようにします.
- (void)buttonDown
{
    NSNotification *notification = [NSNotification notificationWithName:kNotificationName
                                                                 object:@"object"];
    [[NSNotificationQueue defaultQueue] enqueueNotification:notification
                                               postingStyle:NSPostASAP];
    
//    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"object"];
    
    NSLog(@"buttonDown");
    
}

buttonをクリックすると、次のように印刷されます.
2015-03-17 18:22:05.619 AppTest[18557:195583] buttonDown
2015-03-17 18:22:05.636 AppTest[18557:195583] object
2015-03-17 18:22:10.641 AppTest[18557:195583] Action Notification Finish
ここでの間隔から分かるように,通知キューによって通知を管理し,これ以上ブロックされることはない.