iOSiOSiOS

iOS代码同步到主线程的三种方法

2017-03-20  本文已影响11086人  我思__故我在
在APP开发中,很多时候我们需要用多线程的方式下载图片,进行网络请求等,在子线程任务完成后需要刷新主线程的UI,呈现结果。下面介绍三种同步代码到主线程的方法:

查询iOS文档:

@interface NSObject (NSThreadPerformAdditions)

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
    // equivalent to the first method with kCFRunLoopCommonModes

应用:

- (void)updateUIWith:(UIColor *)color{
    
    [self.bottomView setBackgroundColor:color];
}
[self performSelectorOnMainThread:@selector(updateUIWith:) withObject:[UIColor purpleColor] waitUntilDone:YES  modes:[NSArray arrayWithObject:(__bridge NSString*)kCFRunLoopCommonModes]];

参数说明:

  1. (SEL)aSelector
    刷新主线程调用的方法
  2. withObject:(nullable id)arg
    需要传递的参数
  3. modes:(nullable NSArray<NSString *> *)array
    需要传入的数组对象类型是NSString参数类型,由文档可知modes实际需要的参数定义是这样的:
CF_EXPORT const CFStringRef kCFRunLoopDefaultMode;
CF_EXPORT const CFStringRef kCFRunLoopCommonModes;

因此在使用时需要用桥接的方法进行转换。
modes参数是可选的,如果不用该参数,可以直接用文档中下面的方法,并且文档已给说明,此时modes是kCFRunLoopCommonModes的方式。

+ (NSOperationQueue *)mainQueue NS_AVAILABLE(10_6, 4_0);

将需要调用的方法直接添加到主线程中即可,用NSOperationQueue封装的对象方法

- (void)addOperationWithBlock:(void (^)(void))block NS_AVAILABLE(10_6, 4_0);

应用

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [self.bottomView setBackgroundColor:[UIColor redColor]];

        }];
/*!
 * @function dispatch_get_main_queue
 *
 * @abstract
 * Returns the default queue that is bound to the main thread.
 *
 * @discussion
 * In order to invoke blocks submitted to the main queue, the application must
 * call dispatch_main(), NSApplicationMain(), or use a CFRunLoop on the main
 * thread.
 *
 * @result
 * Returns the main queue. This queue is created automatically on behalf of
 * the main thread before main() is called.
 */
DISPATCH_INLINE DISPATCH_ALWAYS_INLINE DISPATCH_CONST DISPATCH_NOTHROW
dispatch_queue_t
dispatch_get_main_queue(void)
{
    return DISPATCH_GLOBAL_OBJECT(dispatch_queue_t, _dispatch_main_q);
}

将调用的方法绑定到主线程,这里用block的方法,当然也是系统封装的方法,实现代码如下:

dispatch_async(dispatch_get_main_queue(), ^{
           
            [self updateUIWith:[UIColor greenColor]];
            
        });

结语

理解不到位的地方,欢迎大家添加指正。
上一篇下一篇

猜你喜欢

热点阅读