NSThread 保留计数

NSThread Retain Count

为什么我线程的Retain count = 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

正如您发现的那样,它是这样工作的: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 保留线程。