iOS NSThread 保活线程代码封装

2020-02-19  本文已影响0人  孙掌门

iOS NSThread 保活线程代码封装

//
//  SCXThread.h
//  blogTest
//
//  Created by 孙承秀 on 2020/2/19.
//  Copyright © 2020 孙承秀. All rights reserved.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface SCXThread : NSObject

/// 开启一个线程
- (void)run;

/// 停止
- (void)stop;

/// 执行一个任务
/// @param block 回调block
- (void)excuteTaskWithBlock:(void(^)(void))block;
@end

NS_ASSUME_NONNULL_END


//
//  SCXThread.m
//  blogTest
//
//  Created by 孙承秀 on 2020/2/19.
//  Copyright © 2020 孙承秀. All rights reserved.
//

#import "SCXThread.h"



@interface SCXNSThread : NSThread

@end
@implementation SCXNSThread
-(void)dealloc{
    NSLog(@"%s",__func__);
}
@end




@interface SCXThread ()
@property(nonatomic,strong)SCXNSThread *thread;
@property(nonatomic,assign)BOOL stopped;
@end
@implementation SCXThread
-(instancetype)init{
    if (self = [super init]) {
        self.stopped = NO;
        __weak typeof(self)weakSelf = self;
        self.thread = [[SCXNSThread alloc] initWithBlock:^{
            [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
            while (weakSelf && !weakSelf.stopped) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
        }];
    }
    return self;
}
-(void)run{
    [self.thread start];
}
-(void)stop{
    if (!self.thread) {
        return;
    }
    [self performSelector:@selector(_stopRunloop) onThread:self.thread withObject:nil waitUntilDone:YES];
}
-(void)excuteTaskWithBlock:(void (^)(void))block{
    if (!self.thread || !block) {
        return;
    }
    [self performSelector:@selector(_excuteTask:) onThread:self.thread withObject:block waitUntilDone:NO];
}
-(void)dealloc{
    [self stop];
}
- (void)_stopRunloop{
    self.stopped = YES;
    CFRunLoopStop(CFRunLoopGetCurrent());
    self.thread = nil;
}
- (void)_excuteTask:(void (^)(void))block{
    block();
}
@end


上一篇 下一篇

猜你喜欢

热点阅读