三十六、Runloop之(五)Runloop的实际应用

Runloop的实际应用

1. 应用1-线程保活。

自定义持久性子线程

#import "CustomPermanantThread.h"
@interface CustomPermanantThread()
@property (nonatomic,strong) NSThread *thread;
@end
@implementation CustomPermanantThread
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.thread = [[NSThread alloc] initWithBlock:^{
            //初始化source上下文
            CFRunLoopSourceContext context = {0};
            //创建source
            CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
            //runloop里添加source
            CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
            //释放source
            CFRelease(source);
            //运行runloop
            CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e10, false);
        }];
        [self.thread start];
    }
    return self;
}

- (void)excuteDataTask:(TaskBlock)task{
    if (self.thread == nil) return;
    [self performSelector:@selector(__excuteTask:) onThread:self.thread withObject:task waitUntilDone:NO];
}

- (void)stop {
    if (self.thread == nil) return;
    [self performSelector:@selector(__stop) onThread:self.thread withObject:nil waitUntilDone:YES];
}

- (void)__stop {
    CFRunLoopStop(CFRunLoopGetCurrent());
    self.thread = nil;
}

- (void)__excuteTask:(TaskBlock)task{
    if (task != nil) {
        task();
    }
}

- (void)dealloc{
    [self stop];
}
@end

你可能感兴趣的:(三十六、Runloop之(五)Runloop的实际应用)