情景:希望自定義的某些方法只在某個(gè)指定的子線程中執(zhí)行
實(shí)戰(zhàn)一
- 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 ()
//創(chuàng)建子線程
@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實(shí)戰(zhàn)[5237:496282] -[ViewController subThreadTask] -- <RevanThread: 0x604000274c40>{number = 4, name = (null)}
2018-08-06 20:55:22.237535+0800 02-RunLoop實(shí)戰(zhàn)[5237:496282] -[ViewController subThreadTask] -- <RevanThread: 0x604000274c40>{number = 4, name = (null)}
2018-08-06 20:55:22.899790+0800 02-RunLoop實(shí)戰(zhàn)[5237:496282] -[ViewController subThreadTask] -- <RevanThread: 0x604000274c40>{number = 4, name = (null)}
- 分析:每點(diǎn)擊一下屏幕就在創(chuàng)建的子線程中執(zhí)行subThreadTask方法图毕。上面的情景要求已經(jīng)初步實(shí)現(xiàn)了当叭。但是控制器存在循環(huán)引用
線程無法釋放
- 測試代碼
#import "ViewController.h"
#import "RevanThread.h"
@interface ViewController ()
//創(chuàng)建子線程
@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引用計(jì)數(shù):%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
- 打印輸出