在非ARC应用程序中,我有一个NSOperation子类,它由一个委托排队,看起来像:
// note that the delegate and element properties are retained
-(id)initWithDelegate:(id<SomeDelegate>)inDelegate element:(SomeElement *)inElement
{
if (self = [super init])
{
[self setDelegate:inDelegate];
[self setElement:inElement];
}
}
-(void)dealloc
{
[_delegate release];
[_element release];
[super dealloc];
}
-(void)main
{
// do stuff
dispatch_async(dispatch_get_main_queue(), ^{
[[self delegate] doSomething:[self element]];
});
}
由于[[self delegate] doSomething:[self element]]将在我的NSOperation对象可能已被解除分配后被调用,我是否需要确保保留&#34; element&#34;在将此操作添加到队列之前的委托中?元素对象保留在应用程序的其他位置,但可能会在那里释放。我需要确保当我的代表从NSOperation收到它时,它仍然是一个有效的对象。
只是想知道在dispatch_async中调用它的行为是否会保留传递给它的参数。我当然可以使用NSInvocation和performSelectorOnMainThread来保留它。
答案 0 :(得分:5)
队列将在其排队时保留该块,并且该块将保留其捕获的对象,例如self
。由于此处self
强烈引用其element
,因此element
至少在阻止运行之后才有效。
请注意,对象对其代理人有强烈的引用是不常见的:确保您没有在那里保持不间断的保留周期。