ARC的手动对象生存期 [英] Manual object lifetime with ARC
问题描述
检查以下代码,并假设它是在ARC下编译的:
Examine the following code, and assume it was compiled under ARC:
- (void)foo {
NSOperationQueue *oq = [[NSOperationQueue alloc] init];
[oq addOperationWithBlock:^{
// Pretend that we have a long-running operation here.
}];
}
尽管将操作队列声明为局部变量,但只要其具有正在运行的操作,其生存期就会超出该方法的范围.
Although the operation queue is declared as a local variable, its lifetime continues beyond the scope of the method as long as it has running operations.
这是如何实现的?
更新:
我感谢罗伯·梅诺夫(Rob Mayoff)的深思熟虑的评论,但我认为我没有正确提出问题.我不是在问关于NSOperationQueue的特定问题,而是在问关于ARC对象寿命的一般问题.具体来说,我的问题是这样的:
I appreciate Rob Mayoff's well-thought-out comments, but I think I did not ask my question correctly. I am not asking a specific question about NSOperationQueue, but rather a general question about object lifetime in ARC. Specifically, my question is this:
在ARC下,对象如何才能参与其自身生命周期的管理?
我从事程序员已经很长时间了,并且我很清楚这种事情的陷阱.我不希望就这是一个好主意还是不好的主意进行演讲.我认为总的来说这是一个不好的选择.相反,我的问题是学术性的:这是一个好主意还是不好的主意,人们将如何在ARC中做到这一点?这样做的具体语法是什么?
I've been a programmer for a very long time, and I'm well aware of the pitfalls of such a thing. I am not looking to be lectured as to whether this is a good or bad idea. I think in general it is a bad one. Rather, my question is academic: Whether it's a good or bad idea or not, how would one do this in ARC and what is the specific syntax to do so?
推荐答案
一般而言,您可以保留对自己的引用.例如:
As a general case you can keep a reference to yourself. E.g.:
@implementation MasterOfMyOwnDestiny
{
MasterOfMyOwnDestiny *alsoMe;
}
- (void) lifeIsGood
{
alsoMe = self;
}
- (void) woeIsMe
{
alsoMe = nil;
}
...
@end
这篇关于ARC的手动对象生存期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!