1. 程式人生 > >[iOS] performSelector:withObject:afterDelay:呼叫沒有作用的問題及解決方法

[iOS] performSelector:withObject:afterDelay:呼叫沒有作用的問題及解決方法

這個問題找了將近一天,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 = [NSInvocationinvocationWithMethodSignature:sig];

    [invo setTarget:self];

    [invo setSelector:aSelector];

    [invo setArgument:&anArgument atIndex:2];

    [invo retainArguments];

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

NSInvocation *invoMT = [NSInvocationinvocationWithMethodSignature: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:nilwaitUntilDone:NO];

}

@end