一、方法集
1、同步执行
这三个方法,均为同步执行,与线程无关,主线程和子线程中均可调用成功。等同于直接调用该方法。在需要动态的去调用方法的时候去使用。
例如:[self performSelector:@selector(test2)];与[self test2];执行效果上完全相同。
- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)object;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
2、异步执行
这两个方法为异步执行,即使delay传参为0,仍为异步执行。只能在主线程中执行,在子线程中不会调到aSelector方法。
由于是在主线程中执行aSelector,所以不会开启子线程。
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes;
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;
在方法未到执行时间之前,取消方法为:
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument;
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget;
注意:调用该方法之前或在该方法所在的viewController生命周期结束的时候去调用取消函数,以确保不会引起内存泄露。
3、主线程执行
这两个方法,在主线程和子线程中均可执行,均会调用主线程的aSelector方法;
- 当前线程为主线程
- 如果设置wait为YES,等待主线程执行完aSelector以后,继续执行主线程;
- 如果设置wait为NO,执行完主线程之后,执行aSelector;
- 当前线程为子线程
- 如果设置wait为YES,等待主线程执行完aSelector以后,继续执行子线程;
- 如果设置wait为NO,不等待主线程执行完aSelector,继续执行子线程;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array;
// equivalent to the first method with kCFRunLoopCommonModes
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
4、子线程执行
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
5、开启子线程在后台运行
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg
二、performSelectorOnMainThread支持多个参数
@interface NSObject(PGPerformSelectorOnMainThreadWithTwoObjects)
- (void) performSelectorOnMainThread:(SEL)selector withObject:(id)arg1 withObject:(id)arg2 waitUntilDone:(BOOL)wait;
@end
@implementation(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