简体   繁体   English

ARC的线程和对象生命周期

[英]Threading and Object Lifetimes with ARC

As I understand ARC, without a strong reference to an object, it is fair game to be collected (since its reference count is 0). 据我所知,ARC没有对对象的强烈引用,因此收集公平游戏(因为它的引用计数为0)。

If, in a method in class A, I do this: 如果,在A类的方法中,我这样做:

ClassB* b = [[ClassB alloc] init];
[b doStuff];

And in doStuff, I do this: 在doStuff中,我这样做:

NSThread* t = [[NSThread alloc] initWithTarget:self selector:@selector(theThread) object:nil];
[t start];

The reference count of b appears to be 0 since it went out of scope after the method in class A finishes. b的引用计数似乎为0,因为它在A类方法完成后超出了范围。 However, a thread is currently 'running' in ClassB and will need local resources. 但是,一个线程当前在ClassB中“运行”并且需要本地资源。

What is the behavior here? 这里的行为是什么? Or perhaps, what should the behavior here be to make sure that b stays around until the thread is all finished? 或许,这里的行为应该是什么来确保b保持不变直到线程全部完成?

Thanks! 谢谢!

The documentation for initWithTarget:selector:object: says that the thread takes ownership of (keeps a strong reference to) its target. initWithTarget:selector:object:文档initWithTarget:selector:object:表示该线程拥有其目标的所有权(保持强引用)。 The target will be released when the thread object is destroyed. 线程对象被销毁时将释放目标。

Be aware that this can cause a retain cycle, if the target also owns the NSThread . 请注意,如果目标也拥有NSThread ,这可能会导致保留周期。

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

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