但沒有測試在子線程中再建立個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