gpt4 book ai didi

ios - NSThread 保留计数

转载 作者:行者123 更新时间:2023-11-29 02:08:28 27 4
gpt4 key购买 nike

为什么我线程的 Retain count = 2?它在启动方法后增加,为什么?
Retain 计数如何为 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 保留线程。

关于ios - NSThread 保留计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29532227/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com