Runloop - 线程保活

#import "ThreadHelper.h"

@interface ThreadHelper ()

@property (strong, nonatomic) NSThread *thread;
@property (assign, nonatomic, getter=isStopped) BOOL stopped;

@end

@implementation ThreadHelper

- (instancetype)init {
    if (self = [super init]) {
        self.stopped = NO;
        __weak __typeof(self)weakSelf = self;
        self.thread = [[NSThread alloc] initWithBlock:^{
            [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
            while (weakSelf && !self.isStopped) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
        }];
    }
    return self;
}

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

- (void)run {
    if (self.thread) {
        [self.thread start];
    }
}

- (void)executeTask:(void (^)(void))task {
    if (task && self.thread) {
        [self performSelector:@selector(__executeTask:) onThread:self.thread withObject:task waitUntilDone:NO];
    }
}

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

#pragma mark - Private

- (void)__executeTask:(void (^)(void))task {
    if (task) {
        task();
    }
}

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

@end

你可能感兴趣的:(Runloop - 线程保活)