RunLoop实战

2018-08-07  本文已影响11人  紫荆秋雪_文

情景:希望自定义的某些方法只在某个指定的子线程中执行

实战一

#import <Foundation/Foundation.h>

@interface RevanThread : NSThread

@end


#import "RevanThread.h"

@implementation RevanThread

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

@end
#import "ViewController.h"
#import "RevanThread.h"

@interface ViewController ()
//创建子线程
@property (nonatomic, strong) RevanThread *subThread;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.subThread = [[RevanThread alloc] initWithTarget:self selector:@selector(threadInit) object:nil];
    [self.subThread start];
}

- (void)threadInit {
    NSLog(@"初始化线程----begain --%@", [NSThread currentThread]);
    [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
    NSLog(@"初始化线程----end  --%@", [NSThread currentThread]);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self performSelector:@selector(subThreadTask) onThread:self.subThread withObject:nil waitUntilDone:NO];
}

- (void)subThreadTask {
    NSLog(@"%s -- %@", __func__, [NSThread currentThread]);
}
@end
2018-08-06 20:55:18.714750+0800 02-RunLoop实战[5237:496282] -[ViewController subThreadTask] -- <RevanThread: 0x604000274c40>{number = 4, name = (null)}
2018-08-06 20:55:22.237535+0800 02-RunLoop实战[5237:496282] -[ViewController subThreadTask] -- <RevanThread: 0x604000274c40>{number = 4, name = (null)}
2018-08-06 20:55:22.899790+0800 02-RunLoop实战[5237:496282] -[ViewController subThreadTask] -- <RevanThread: 0x604000274c40>{number = 4, name = (null)}

线程无法释放

#import "ViewController.h"
#import "RevanThread.h"

@interface ViewController ()
//创建子线程
@property (nonatomic, strong) RevanThread *subThread;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.subThread = [[RevanThread alloc] initWithBlock:^{
        [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
        NSLog(@"初始化线程----end  --%@", [NSThread currentThread]);
    }];
    [self.subThread start];
}

- (void)threadInit {
    NSLog(@"初始化线程----begain --%@", [NSThread currentThread]);
    [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
    NSLog(@"初始化线程----end  --%@", [NSThread currentThread]);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"self引用计数:%ld", (long)CFGetRetainCount((__bridge CFTypeRef)(self)));
    [self performSelector:@selector(subThreadTask) onThread:self.subThread withObject:nil waitUntilDone:NO];
}

- (void)subThreadTask {
    NSLog(@"%s -- %@", __func__, [NSThread currentThread]);
}

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

@end
上一篇 下一篇

猜你喜欢

热点阅读