[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 = [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




评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值