美文网首页
iOS多线程之NSThread

iOS多线程之NSThread

作者: 芝麻酱的简书 | 来源:发表于2019-01-15 17:13 被阅读1次

优点:NSThread 比其他两个轻量级
缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销

NSThread 创建方式:

显式创建线程的方法:

[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil]; 
NSThread* myThread = [[NSThread alloc] initWithTarget:selfselector:@selector(doSomething:)object:nil]; 
[myThread start];

不显式创建线程的方法:

[self performSelectorInBackground:@selector(startCount) withObject:nil];

线程间通讯

线程下载完图片后怎么通知主线程更新界面呢?

[self performSelectorOnMainThread: @selector(updateUI:) 
                       withObject: image 
                    waitUntilDone: YES]; 

系统提供的线程通讯方法:

- (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)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
    // equivalent to the first method with kCFRunLoopCommonModes
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));

相关文章

网友评论

      本文标题:iOS多线程之NSThread

      本文链接:https://www.haomeiwen.com/subject/upiydqtx.html