想象三个班级。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释放,并且delegateforavcInstance不再有效。
理想情况下,我想将classBInstance(self in ClassB) 的所有权与avcInstance; 当avcInstance被释放时,classBInstance或者代表被释放。
或者,我可以classBInstance在 -中进行清理cleanupCalledByDelegate,这是在发布之前调用avcInstance的。
如何最好地处理这个?我宁愿不创建ClassB *classBInstanceClassA 的属性,因为那样我就必须让它发布classBInstance,而且我更愿意在 ClassB 中处理它。如果这是最好的解决方案,我会使用块并在 ClassA 中传递一个完成块:
{
classBInstance = nil;
}
to -goWithOptions,我会打电话给-cleanupCalledByDelegate。这是处理这个问题的正确方法吗?