[iOS] performSelector:withObject:afterDelay:調用沒有作用的問題及解決方案

來源:互聯網
上載者:User
這個問題找了將近一天,baidu、google了很久,竟然沒有人遇到同樣問題?
performSelector:withObject:afterDelay:和[NSTimer timerWithTimeInterval:invocation:repeats:]都存在此問題:調用後,延遲後(延遲0也一樣)沒有進入指定的@selecter()中。反覆驗證發現,這種現象出現在子線程中,主線程中可正常使用。因此必須保證調用performSelector:withObject:afterDelay:是在主線程中。

但沒有測試在子線程中再建立個NSTimer用來延遲,應該也可以,反正直接用
[NSTimer timerWithTimeInterval:invocation:repeats:]是不行的。
特實現
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
方法,保證在主線程中調用成功

//  NSObject_performSelectorEx.h

@interface NSObject (performSelectorEx)

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;

@end

//  NSObject_performSelectorEx.m

#import
"NSObject_performSelectorEx.h"

@implementation NSObject (performSelectorEx)

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay

{

   
NSMethodSignature *sig = [self
methodSignatureForSelector:aSelector];

   
if (!sig)

    {

       
return;

    }

    

   
NSInvocation *invo = [NSInvocation
invocationWithMethodSignature:sig];

    [invo
setTarget:self];

    [invo
setSelector:aSelector];

    [invo
setArgument:&anArgument atIndex:2];

    [invo
retainArguments];

   
NSMethodSignature *sigMT = [invo methodSignatureForSelector:@selector(performSelector:withObject:afterDelay:)];

   
NSInvocation *invoMT = [NSInvocation
invocationWithMethodSignature:sigMT];

    [invoMT
setTarget:invo];

    [invoMT
setSelector:@selector(performSelector:withObject:afterDelay:)];

   
SEL arg1 = @selector(invoke);

   
void *arg2 = nil;

   
NSTimeInterval arg3 = delay;

    [invoMT
setArgument:&arg1 atIndex:2];

    [invoMT
setArgument:&arg2 atIndex:3];

    [invoMT
setArgument:&arg3 atIndex:4];

    [invoMT
retainArguments];

    [invoMT
performSelectorOnMainThread:@selector(invoke)
withObject:nil
waitUntilDone:NO];

}

@end

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.