Test whether iOS's Notification is synchronous or asynchronous

The interview was asked this question, it was not very clear, write a code test and record it.

#pragma mark - test notification-
(void)testNotification
{
    // initialize a button
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
    button.backgroundColor = [UIColor orangeColor];
    [ button setTitle:@"Trigger notification" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonDown) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    // Register notification
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector:@selector(actionNotification:)
                                                 name:kNotificationName
                                               object:nil];
}
- (void) actionNotification: (NSNotification*)notification
{
    NSString* message = notification.object;
    NSLog(@"message: %@",message);
    
    sleep(3); // sleep for 3 seconds
    NSLog(@"Notification speaks end");
}

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

After clicking the trigger notification button, the console prints the following:

It can be seen from the time interval here that the notification process is performed synchronously.

After the notification is thrown, the observer will continue to execute after the notification event processing is completed (here we sleep for 3 seconds), which means that the process is synchronous by default; when the notification is sent, the notification center will Wait until all observers have received and processed the notification before returning to the poster;

PS:

If you want to change from synchronous to asynchronous, there is also a way. For example, let the notification event handling method be executed in the child thread.

- (void) actionNotification: (NSNotification*)notification
{
// NSString* message = notification.object;
// NSLog(@"message: %@",message);
//
// sleep(3); // sleep 3 Seconds
// NSLog(@"Notification end");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString* message = notification.object;
        NSLog(@"message:%@",message);
        
        sleep(3);
        
        NSLog(@"Notification of speaking end:%@",[NSThread currentThread]);
        
    });
}

- (void)buttonDown
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"Notification of speaking start"];
    NSLog(@" button to speak: %@",[NSThread currentThread]);
}

At this point, click the trigger notification button, and the console prints the input:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324986960&siteId=291194637