iOS NTThread 与 NSRunLoop 使用

使用

示例代码,通过创建 OMTThread 实例,并开启线程。使用 NSTimer 每 3 秒执行一次方法。

#import "ThreadViewController.h"
#import "OMTThread.h"


static NSString *const kThreadName = @"org.yzr.thread";

@interface ThreadViewController ()

@property (nonatomic, strong) OMTThread *thread;

@end

@implementation ThreadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.thread start];
    
    NSTimer *timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(excute) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

- (void)excute {
    [self callBlock:^{
        NSLog(@"thread name:%@", [NSThread currentThread].name);
        NSLog(@"我在执行方法");
    } onThread:self.thread];
}

- (OMTThread *)thread {
    if (!_thread) {
        _thread = [[OMTThread alloc] initWithName:kThreadName qos:NSQualityOfServiceUserInteractive];
    }
    return _thread;
}
@end

OMTThread.h

#import 

@interface OMTThread : NSThread
/// 初始化
- (instancetype)initWithName:(NSString *)name qos:(NSQualityOfService)qos;

@end

@interface NSObject (OMTThreadPerformAdditions)
/// 在指定线程中执行 block
- (void)callBlock:(dispatch_block_t)block onThread:(NSThread *)thread;

@end

OMTThread.m

#import "OMTThread.h"
#import 

@implementation OMTThread

- (instancetype)initWithName:(NSString *)name qos:(NSQualityOfService)qos {
    if (self = [super initWithTarget:self.class selector:@selector(runRunLoop) object:nil]) {
        self.qualityOfService = qos;
        self.name = name;
    }
    return self;
}

+ (void)runRunLoop {
    @autoreleasepool {
        // 设置线程名字
        pthread_setname_np([NSThread currentThread].name.UTF8String);
        
        // 设置虚拟的 runloop 源,避免旋转
        CFRunLoopSourceContext noSpinCtx = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
        CFRunLoopSourceRef noSpinSource = CFRunLoopSourceCreate(NULL, 0, &noSpinCtx);
        CFRunLoopAddSource(CFRunLoopGetCurrent(), noSpinSource, kCFRunLoopDefaultMode);
        CFRelease(noSpinSource);
        
        // 运行 RunLoop
        while (kCFRunLoopRunStopped != CFRunLoopRunInMode(kCFRunLoopDefaultMode, ((NSDate *)[NSDate distantFuture]).timeIntervalSinceReferenceDate, NO)) {
            NSLog(@"退出 Runloop");
        }
    }
}

@end

@implementation NSObject (OMTThreadPerformAdditions)

- (void)callBlock:(dispatch_block_t)block onThread:(NSThread *)thread {
    [self performSelector:@selector(_excuteBlock:) onThread:thread withObject:block waitUntilDone:NO];
}

- (void)_excuteBlock:(dispatch_block_t)block {
    if (block) {
        block();
    }
}

@end

你可能感兴趣的:(iOS NTThread 与 NSRunLoop 使用)