为什么我的线程的保留计数= 2?它在开始方法之后会增加,为什么?
如何为NSThreads保留计数?
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSThread *thread;
@autoreleasepool
{
thread = [[NSThread alloc] initWithTarget:self selector:@selector(check) object:nil];
NSLog(@"RC == %lu",(unsigned long)[thread retainCount]);
[thread start];
}
NSLog(@"RC == %lu",(unsigned long)[thread retainCount]);
}// presently stopped here on breakpoint
-(void)check{
for (int i = 0 ; i< 100000; i++) {
NSLog(@"NEW THREAD ==%d",i);
}
}
@end发布于 2015-04-09 07:35:02
正如您所发现的,这就是它的工作方式:start将保留您的NSThread,这样它就能在执行过程中存活下来。一旦您完成了保留计数,+[NSThread exit]就会减少。
另一方面,考虑到这一点:您正在创建一个NSThread,并将其(保留的)引用分配给一个局部变量。你打算怎么削减它?局部变量在viewDidLoad之外是不可见的,因此不能释放它。
正确的处理方法是为您的NSThread实例使用ivar,因此您可以在dealloc中发布它,或者使用autoreleased NSThread,这取决于start将保留该对象。所以你可以:
- (void)viewDidLoad {
[super viewDidLoad];
NSThread *thread;
@autoreleasepool
{
thread = [[[NSThread alloc] initWithTarget:self selector:@selector(check) object:nil] autorelease];
NSLog(@"RC == %lu",(unsigned long)[thread retainCount]);
[thread start];
}一切都会正确的。
我希望这能解释为什么start保留线程。
https://stackoverflow.com/questions/29532227
复制相似问题