[iOS] performSelector:withObject:afterDelay:调用没有作用的问题及解决方法

http://blog.csdn.net/onlyou930/article/details/7569158

这个问题找了将近一天,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

你可能感兴趣的:(ios,perform)