想象三个班级。ClassA 和 ClassB 是我的。第三类是 UIViewController 我无法修改其代码:
在 A 类:
- (void) aMethod
{
ClassB *classBInstance = [[[ClassB alloc] init] goWithOptions:options];
}
ClassBInstance
仅在 的生命周期内保留aMethod
。
B类:
- (void) goWithOptions
{
AUIViewController *avcInstance = [[AUIViewController alloc] init];
avcInstance.delegate = self;
[viewController pushViewController:avcInstance animated: YES]; // this returns immediately, but we need self to be retained until the delegate is done with it
}
- (void) cleanupCalledByDelegate //
{
// cleanup
}
当-goWithOptions
方法被调用时,avcInstance
被调用者保留,但传递给的 selfdelegate
不是。这意味着一旦-goWithOptions
返回并aMethod
完成,然后classBInstance
释放,并且delegate
foravcInstance
不再有效。
理想情况下,我想将classBInstance
(self in ClassB) 的所有权与avcInstance
; 当avcInstance
被释放时,classBInstance
或者代表被释放。
或者,我可以classBInstance
在 -中进行清理cleanupCalledByDelegate
,这是在发布之前调用avcInstance
的。
如何最好地处理这个?我宁愿不创建ClassB *classBInstance
ClassA 的属性,因为那样我就必须让它发布classBInstance
,而且我更愿意在 ClassB 中处理它。如果这是最好的解决方案,我会使用块并在 ClassA 中传递一个完成块:
{
classBInstance = nil;
}
to -goWithOptions
,我会打电话给-cleanupCalledByDelegate
。这是处理这个问题的正确方法吗?