1、GCD的dispatch_async方法
dispatch_async(dispatch_get_main_queue, ^{
// do something
});
该方法用的最为普遍,AFNetworking和SDWebImage等很多开源库都采用这种方式,
如AFNetworking
dispatch_async(dispatch_get_main_queue(), ^{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
});
SDWebImage
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenterdefaultCenter]postNotificationName:SDWebImageDownloadStartNotificationobject:self];
});
2、NSObject的performSelectorOnMainThread方法
该方法在NSThread头文件中以NSObject的category方式声明。
NSThread.h
@interface NSObject (NSThreadPerformAdditions)
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullableid)arg waitUntilDone:(BOOL)wait;
@end
@implementation NSObject (XXXX)
- (void)excuteBlock:(dispatch_block_t)block
{
block();
}
- (void)asynPerformBlockOnMainThread:(dispacth_bock_t)block
{
block = [block copy];
[selfperformSelectorOnMainThread:@selector(excuteBlock:)
withObject:block
waitUntilDone:NO];
}
@end
3、使用NSOperationQueue
可以细分为两种方法,第一种:
[[NSOperationQueuemainQueue]addOperationWithBlock:^{
// do something
}];
第二种:
将工作内容封装在NSOperation中,然后[[NSOperationQueue mainQueue] addOperation:myOperation];
4 、NSRunLoop
@interface NSRunLoop (NSOrderedPerform)
- (void)performSelector:(SEL)aSelector target:(id)target argument:(nullableid)arg order:(NSUInteger)order modes:(NSArray<NSString *> *)modes;
@end
[[NSRunLoop mainRunLoop] performSelector: target: argument: order: modes:];
该方法没有在项目中实际使用过。提一个额外话题,dispatch_get_main_queue、mainThread、mainQueue以及mainRunLoop的之间的关系?
这里扩展一下,延迟执行block的方法有哪些?
1、
NSRunLoop.h
@interface NSObject (NSDelayedPerforming)
- (void)performSelector:(SEL)aSelector withObject:(nullableid)anArgument afterDelay:(NSTimeInterval)delay;
@end2、GCD的dispatch_after方法
注意延迟执行有个雷区,代码如下:
- (void)fireBlock:(dispatch_block_t)block {
block();
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self performSelector:@selector(fireBlock:) withObject:^{
NSLog(@"hello world");
} afterDelay:0.3];
});
上面的代码片段原有的目的是异步延迟0.3秒后输出Hello world。但是运行之后发现不会输出Hello world。
原因是:非主线程的NSRunLoop默认没有开启,而
- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;函数内部是通过NSTimer定时器实现,在NSRunLoop没有开启的情况下,NSTimer不会得到正常运行。