PerformSelector withObject afterDelay does not run in the sub-thread call. performselector

Source: Internet
Author: User

PerformSelector withObject afterDelay does not run in the sub-thread call. performselector

For example, this is a problem found recently when I modified a Data Synchronization module. The entire data synchronization task is placed in a background thread after the App is started. After a single data synchronization task is successfully executed

Objective-c code
  1. [Self defined mselector :( nonnull SEL) withObject :( nullable id) afterDelay :( NSTimeInterval)];

To execute the next single data synchronization task. Through debugging, it is found that the SEL method is not called when this line of code is executed. After determining the existence of this method, I never thought of the reason, So Google. The answer is that the performSelector withObject afterDelay method does not call the SEL method in the Child thread, and the performSelector withObject method is called directly. The reason is:

1. afterDelay uses the timer of the current thread to call SEL after a certain time, and NO AfterDelay directly calls SEL.
2. There is no timer in the Child thread by default.


Therefore, there are two solutions to the problem:

1. Enable the thread Timer

Objective-c code
  1. [[Nsunloop currentRunLoop] run];


2. Run the scheduled task with dispatch_after.


Objective-c code
    1. -(Void) functionToDelay :( SEL) function param :( nullable id) param afterDelay :( NSTimeInterval) delay {
    2. Dispatch_time_t time = dispatch_time (DISPATCH_TIME_NOW, delay * NSEC_PER_SEC );
    3. Dispatch_after (time, dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    4. If ([self respondsToSelector: function]) {
    5. # Pragma clang diagnostic push
    6. # Pragma clang diagnostic ignored "-Warc-starter mselector-leaks"
    7. [Self defined mselector: function withObject: param];
    8. # Pragma clang diagnostic pop
    9. }
    10. });
    11. }

QQ technology exchange group 290551701

Related Article

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: 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.