The interview was asked this question, not very clear, write code test and record.
#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];
Registration Notice
[[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 (@ "Notify End of Speech");
}
-(void) Buttondown
{
[[Nsnotificationcenter Defaultcenter] postnotificationname:knotificationname object:@ "Notice to talk start"];
NSLog (@ "button to speak");
}
When you click the Trigger Notification button, the console prints as follows:
Through the time interval here, we can see that the notification process is synchronous.
After the notification is thrown, the viewer will not proceed until the notification event is completed (Here we hibernate for 3 seconds), that is, the process is synchronized by default, and when the notification is sent, the notification center waits for all observer to receive and process the notification before returning to poster;
Ps:
If you want to change synchronization to asynchronous, there is 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 for 3 seconds.
NSLog (@ "Notify End of Speech");
Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{
nsstring* message = Notification.object;
NSLog (@ "message:%@", message);
Sleep (3);
NSLog (@ "Notify End of speech:%@", [Nsthread CurrentThread]);
});
}
-(void) Buttondown
{
[[Nsnotificationcenter Defaultcenter] postnotificationname:knotificationname object:@ "Notice to talk start"];
NSLog (@ "button Talk:%@", [Nsthread CurrentThread]);
}
At this point, click the Trigger Notification button and the console prints the input:
Test whether iOS notification is synchronous or asynchronous