Runloop应用:线程保活
2017-08-15 本文已影响0人
南城同學
应用场景:
- 经常在子线程中做事情。
实现:
-
实现逻辑:
- 创建一个子线程;
- 在子线程里添加一个runloop。
-
封装实现:
typedef void (^PermenantThreadTask)(void);
@interface PermenantThread : NSObject
/**
在当前子线程执行一个任务
*/
- (void)executeTask:(PermenantThreadTask)task;
/**
结束线程
*/
- (void)stop;
@end
@interface PermenantThread()
@property (strong, nonatomic) NSThread *innerThread;
@property (assign, nonatomic, getter=isStopped) BOOL stopped;
@end
@implementation PermenantThread
- (instancetype)init {
if (self = [super init]) {
self.stopped = NO;
__weak typeof(self) weakSelf = self;
self.innerThread = [[NSThread alloc] initWithBlock:^{
[[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
while (weakSelf && !weakSelf.isStopped) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}];
[self.innerThread start];
}
return self;
}
- (void)executeTask:(PermenantThreadTask)task {
if (!self.innerThread || !task) return;
[self performSelector:@selector(__executeTask:) onThread:self.innerThread withObject:task waitUntilDone:NO];
}
- (void)stop {
if (!self.innerThread) return;
[self performSelector:@selector(__stop) onThread:self.innerThread withObject:nil waitUntilDone:YES];
}
- (void)dealloc {
NSLog(@"%s", __func__);
[self stop];
}
#pragma mark - private methods
- (void)__stop {
self.stopped = YES;
CFRunLoopStop(CFRunLoopGetCurrent());
self.innerThread = nil;
}
- (void)__executeTask:(PermenantThreadTask)task {
task();
}
@end