情景:希望自定义的某些方法只在某个指定的子线程中执行
实战一
- RevanThread
#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)}
- 分析:每点击一下屏幕就在创建的子线程中执行subThreadTask方法。上面的情景要求已经初步实现了。但是控制器存在循环引用
线程无法释放
- 测试代码
#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
- 打印输出