iOS 底层 - runloop之用OC实现线程保活

2020-04-06  本文已影响0人  水中的蓝天

本文源自本人的学习记录整理与理解,其中参考阅读了部分优秀的博客和书籍,尽量以通俗简单的语句转述。引用到的地方如有遗漏或未能一一列举原文出处还望见谅与指出,另文章内容如有不妥之处还望指教,万分感谢 !

XYHPermenantThread

XYHPermenantThread.h

typedef void (^XYHPermenantThreadTask)(void);

@interface XYHPermenantThread : NSObject

/**
 在当前子线程执行一个任务
 */
- (void)executeTask:(XYHPermenantThreadTask)task;

/**
 结束线程
 */
- (void)stop;

@end

XYHPermenantThread.m

#import "XYHPermenantThread.h"

/** XYHThread **/
@interface XYHThread : NSThread
@end
@implementation XYHThread
- (void)dealloc
{
    NSLog(@"%s", __func__);
}
@end

/** XYHPermenantThread **/
@interface XYHPermenantThread()
@property (strong, nonatomic) XYHThread *innerThread;
@property (assign, nonatomic, getter=isStopped) BOOL stopped;
@end

@implementation XYHPermenantThread
#pragma mark - public methods
- (instancetype)init
{
    if (self = [super init]) {
        self.stopped = NO;
        
        __weak typeof(self) weakSelf = self;
        
        self.innerThread = [[XYHThread alloc] initWithBlock:^{
            [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
            
            while (weakSelf && !weakSelf.isStopped) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
        }];
        
        [self.innerThread start];
    }
    return self;
}

- (void)executeTask:(XYHPermenantThreadTask)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__);
    
    [self stop];
}

#pragma mark - private methods
- (void)__stop
{
    self.stopped = YES;
    CFRunLoopStop(CFRunLoopGetCurrent());
    self.innerThread = nil;
}

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

@end

使用:-------->>>>>>>>>>>>>>>--------

#import "ViewController.h"
#import "XYHPermenantThread.h"

@interface ViewController ()
@property (strong, nonatomic) XYHPermenantThread *thread;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.thread = [[XYHPermenantThread alloc] init];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.thread executeTask:^{
        NSLog(@"执行任务 - %@", [NSThread currentThread]);
    }];
}

- (IBAction)stop {
    [self.thread stop];
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
}
上一篇下一篇

猜你喜欢

热点阅读