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
网友评论