performSelector withObject afterDelay 在子線程上調用不運行,performselector

來源:互聯網
上載者:User

performSelector withObject afterDelay 在子線程上調用不運行,performselector

如題,這是最近在修改一個資料同步模組時發現的問題。整個資料同步的任務是在App啟動後放在一個後台執行的線程中的,執行某個單條資料同步任務成功後,會使用

Objective-c代碼  
  1. [self performSelector:(nonnull SEL) withObject:(nullable id) afterDelay:(NSTimeInterval)];  

 來執行下一個單條資料同步任務。通過調試,發現在執行到這行代碼的時候,並沒有調用 SEL 的方法。在確定存在這個方法後,一直沒有想到原因,於是就Google之。答案就是,performSelector withObject afterDelay 方法在子線程中,並不會調用SEL方法,而 performSelector withObject 方法會直接調用。原因在於一下兩點:

1、afterDelay方式是使用當前線程的定時器在一定時間後調用SEL,NO AfterDelay方式是直接調用SEL。
2、子線程中預設是沒有定時器的。

 

所以,針對問題的解決方案也有兩種:

1、開啟線程的定時器

Objective-c代碼  
  1. [[NSRunLoop currentRunLoop] run];  

 

2、使用dispatch_after來執行定時任務

 

Objective-c代碼  
    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-performSelector-leaks"  
    7.         [self performSelector:function withObject:param];  
    8. #pragma clang diagnostic pop  
    9.   
    10.         }  
    11.     });     
    12. }  

QQ技術交流群290551701  http://cxy.liuzhihengseo.com/556.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.