Unlike the event mechanism in JavaScript, the event broadcast mechanism in iOS is synchronous, and by default broadcasts a notification that blocks the following code:
OBJC Code
- -(void) clicked
- {
- Nsnotificationcenter *center = [Nsnotificationcenter defaultcenter];
- [Center postnotificationname:@"Event_happend" object:self];
- NSLog (@"all handler Done");
- }
After you press the button, send a broadcast that has already registered 2 listeners for this event
OBJC Code
- -(ID) init
- {
- self = [super init];
- if (self) {
- [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (whenreceive:) name:@"Event_happend" Object:nil];
- }
- return self;
- }
- -(void) Whenreceive: (nsnotification*) notification
- {
- NSLog (@"im1111");
- }
OBJC Code
- -(ID) init
- {
- self = [super init];
- if (self) {
- [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (whenreceive:) name:@"Event_happend" Object:nil];
- }
- return self;
- }
- -(void) Whenreceive: (nsnotification*) notification
- {
- NSLog (@"im22222");
- }
executing this code will first output im1111, then im22222, and finally all handler done. Debugging finds that the code is always running on the same line approached (the thread that broadcasts the event), the code after the broadcast event is blocked until all the listeners have finished responding
So, because of this feature of Notificationcenter, if you want the broadcast event to be handled asynchronously, you need to open a new thread in the listener's method. Notification should be decoupled as a component, rather than using it for asynchronous processing
Whether the notification mechanism of iOS is synchronous or asynchronous