线程保活

ViewController.h


#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface XSYThreadSaveActive : NSObject

/// 执行任务
/// @param task 任务
- (void)executeTask:(void(^)(void))task;

/// 取消任务
- (void)cancelTask;

@end

NS_ASSUME_NONNULL_END



ViewController.m


#import "XSYThreadSaveActive.h"

@interface XSYThread : NSThread

@end

@implementation XSYThread

- (void)dealloc {
    NSLog(@"I am dead %s",__func__);
}

@end

@interface XSYThreadSaveActive ()

@property (strong, nonatomic) XSYThread *thread;
@property (assign, nonatomic, getter = isStop) BOOL stop;

@end

@implementation XSYThreadSaveActive

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

#pragma mark - Public method

// 执行任务
- (void)executeTask:(void (^)(void))task {
    if (!self.thread || !task) {
        return;;
    }
    
    // waitUntilDone这个参数到底是什么意思?
    [self performSelector:@selector(__executeTask:) onThread:self.thread withObject:task waitUntilDone:NO];
    
}

// 取消任务
- (void)cancelTask {
    if (!self.thread) {
        return;
    }
    
    [self performSelector:@selector(stop) onThread:self.thread withObject:nil waitUntilDone:YES];
}


#pragma mark - Private method

// 取消任务
- (void)stop {
    self.stop = YES;
    CFRunLoopStop(CFRunLoopGetCurrent());
    self.thread = nil;
}

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

@end


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。