iOS开发笔记--performSelectorOnMainThread支持多个参数

iOS 的 NSObject对象提供了一种在不同线程中执行其方法的机制。
最常见的是需要在主线程即UI线程中去执行一些方法

performSelectOnMainThread:withObject:waitUntilDone:
但是这个默认的方法只支持一个参数。

performSelector:withObject:withObject:
这个不是在主程线中运行的…只能依靠category来实现

@interface NSObject (PGPerformSelectorOnMainThreadWithTwoObjects)
- (void) performSelectorOnMainThread:(SEL)selector withObject:(id)arg1 withObject:(id)arg2 waitUntilDone:(BOOL)wait;
@end
    @implementation NSObject (PGPerformSelectorOnMainThreadWithTwoObjects)
    - (void) performSelectorOnMainThread:(SEL)selector withObject:(id)arg1 withObject:(id)arg2 waitUntilDone:(BOOL)wait
{
NSMethodSignature *sig = [self methodSignatureForSelector:selector];
if (!sig) return;

NSInvocation* invo = [NSInvocation invocationWithMethodSignature:sig];
[invo setTarget:self];
[invo setSelector:selector];
[invo setArgument:&arg1 atIndex:2];
[invo setArgument:&arg2 atIndex:3];
[invo retainArguments];
    [invo performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:wait];
}
@end

原文: www.voidcn.com/article/p-txtfmgtx-vq.html

猜你喜欢

转载自blog.csdn.net/iDivines/article/details/80191460