block与GCD--42:多用GCD,少用performSelector系列方法

2023-11-22 08:30:49 浏览数 (2)

performSelector系列方法

  • 编译器并不知道将要执行的选择器是什么,也不知道该选择器是否有返回值,所以没有办法运用ARC的内存管理规则判断返回值是不是应该释放
  • 这些方法的返回值只能是void或者对象类型(id)
  • 使用起来传入参数有限
代码语言:javascript复制
- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)object;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;

GCD与performSelector方法对比(尽可能使用GCD)

  • 延时
代码语言:javascript复制
//performSelector
[NSObject performSelector:@selector(dosomething) withObject:nil afterDelay:0.5];

//GCD
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dosomething];
});
  • 主线程执行任务
代码语言:javascript复制
//performSelector
[NSObject performSelectorOnMainThread:@selector(dosomething) withObject:nil waitUntilDone:NO];
    
//GCD
dispatch_async(dispatch_get_main_queue(), ^{
        [self dosomething];
});

0 人点赞