简体   繁体   English

NSThread保留计数

[英]NSThread Retain Count

Why is the Retain count of my thread = 2?? 为什么我的线程的保留计数= 2? It gets incremented after the start method why ? 启动方法后为什么会递增?
How does Retain count work for NSThreads 保留计数对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

This is how it works, as you discovered: start will retain your NSThread so it does live through its execution. 正如您所发现的那样,它是这样工作的: start将保留您的NSThread,使其在执行过程中有效。 +[NSThread exit] will decrement that retain count once you are done with it. +[NSThread exit]将减少保留计数。

On another hand, think about this: you are creating an NSThread and assigning its (retained) reference to a local variable. 另一方面,请考虑一下:您正在创建一个NSThread并将其(保留的)引用分配给局部变量。 How are you going to decrement it? 你要如何减少它? The local variable will not be visible outside of viewDidLoad , so you cannot release it. viewDidLoad之外,本地变量将不可见,因此您无法释放它。

A correct way of handling this is using an ivar for your your NSThread instance, so you can release it in dealloc , or use an autorelease d NSThread , counting on the fact that start will retain that object. 解决此问题的正确方法是为您的NSThread实例使用ivar,因此您可以在start保留该对象的事实下,在dealloc释放它,或使用autorelease d NSThread So you can have: 因此,您可以:

        - (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];
            }

and everything will be correct. 一切都会正确。

I hope this explains why start retains the thread. 我希望这解释了为什么start保留线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM