Whether the notification mechanism of iOS is synchronous or asynchronous

Source: Internet
Author: User

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
  1. -(void) clicked
  2. {
  3. Nsnotificationcenter *center = [Nsnotificationcenter defaultcenter];
  4. [Center postnotificationname:@"Event_happend" object:self];
  5. NSLog (@"all handler Done");
  6. }


After you press the button, send a broadcast that has already registered 2 listeners for this event

OBJC Code
  1. -(ID) init
  2. {
  3. self = [super init];
  4. if (self) {
  5. [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (whenreceive:) name:@"Event_happend" Object:nil];
  6. }
  7. return self;
  8. }
  9. -(void) Whenreceive: (nsnotification*) notification
  10. {
  11. NSLog (@"im1111");
  12. }

OBJC Code
  1. -(ID) init
  2. {
  3. self = [super init];
  4. if (self) {
  5. [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (whenreceive:) name:@"Event_happend" Object:nil];
  6. }
  7. return self;
  8. }
  9. -(void) Whenreceive: (nsnotification*) notification
  10. {
  11. NSLog (@"im22222");
  12. }

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.