1、線程保活管理類.h文件
//
//? ZFPermenantThread.h
//? ZFThread
//
//? Created by zzf on 2020/5/26.
//? Copyright ? 2020 zzf. All rights reserved.
//
#import
NS_ASSUME_NONNULL_BEGIN
@interface ZFPermenantThread : NSObject
- (void)run;
- (void)stop;
- (void)executeTask:(void(^)(void))task;
@end
NS_ASSUME_NONNULL_END
2、線程保活管理類.m文件
//
//? ZFPermenantThread.m
//? ZFThread
//
//? Created by zzf on 2020/5/26.
//? Copyright ? 2020 zzf. All rights reserved.
//
#import "ZFPermenantThread.h"
@interface ZFThread : NSThread
@end
@implementation ZFThread
- (void)dealloc {
? ? NSLog(@"%s",__func__);
}
@end
@interface ZFPermenantThread ()
@property (nonatomic, strong)ZFThread *innerThread;
@property (nonatomic, assign, getter=isStopped)BOOL stopped;
@end
@implementation ZFPermenantThread
- (instancetype)init {
? ? if(self= [superinit]) {
? ? ? ? self.stopped=NO;
? ? ? ? __weaktypeof(self) weakSelf =self;
? ? ? ? self.innerThread= [[ZFThreadalloc]initWithBlock:^{
? ? ? ? ? ? [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc]init] forMode:NSDefaultRunLoopMode];
? ? ? ? ? ? while(weakSelf && !weakSelf.isStopped) {
? ? ? ? ? ? ? ? [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
? ? ? ? ? ? }
? ? ? ? }];
? ? ? ? [self.innerThreadstart];
? ? }
? ? return self;
}
- (void)run{
? ? if(!self.innerThread) {
? ? ? ? return;
? ? }
? ? [self.innerThread start];
}
- (void)executeTask:(void(^)(void))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__);
? ? [selfstop];
}
#pragma mark - private methods
- (void)__stop{
? ? self.stopped=YES;
? ? CFRunLoopStop(CFRunLoopGetCurrent());
? ? self.innerThread = nil;
}
- (void)__executeTask:(void(^)(void))task {
? ? task();
}
@end
3、使用調用
//
//? ViewController.m
//? ZFThread
//
//? Created by zzf on 2020/5/26.
//? Copyright ? 2020 zzf. All rights reserved.
//
#import "ViewController.h"
#import "ZFPermenantThread.h"
@interface ViewController ()
@property (nonatomic, strong)ZFPermenantThread *thread;
@end
@implementation ViewController
- (void)viewDidLoad {
? ? [super viewDidLoad];
? ? // Do any additional setup after loading the view.
? ? self.thread = [[ZFPermenantThread alloc] init];
//? ? [self.thread run];
}
- (void)touchesBegan:(NSSet *)toucheswithEvent:(UIEvent*)event {
? ? [self.thread executeTask:^{
? ? ? ? NSLog(@"執行任務");
? ? }];
}
- (void)test{
}
- (void)stop{
? ? [self.threadstop];
}
- (void)dealloc {
//? ? [self.thread stop];
}
@end