例如,假设我有一个 RootViewController
类和 AnotherViewController
类,我需要更改我的 RootViewController
中的一个属性来自 AnotherViewController
...在 AnotherViewController.h
中拥有“RootViewController”属性是否安全? (这样我就可以访问它的实例变量)?
@interface AnotherViewController : UIViewController {
RootViewController *rootViewController;
}
@property (nonatomic, retain) RootViewController *rootViewController;
@end
@implementation AnotherViewController
@synthesize rootViewController;
- (void)someMethod {
// set the data was added flag, so the rootViewController knows to scroll to the bottom of the tableView to show the new data
self.rootViewController.dataWasAdded = YES;
// if the user came in via a search result, make the search controller's tableView go away
self.rootViewController.searchDisplayController.active = NO;
}
如果这不是一个好主意,有人可以解释为什么吗?
在上面的代码中,我知道我可以使用协议(protocol)/委托(delegate)来处理同样的事情——我猜我可能应该这样做。然而,我读过的书籍或其他 Material 都没有真正讨论过这个问题。
我问的原因是我正在使我的应用程序通用,并使用
UISplitViewController
我注意到当用户在“详细 View ”中进行更改时,我需要经常更新我的“主视图”。所以,我采取了看似简单的路线并开始设置 UIViewControllers
作为属性......但我遇到了一些难以跟踪的内存泄漏和偶尔的崩溃。我读了一些关于“循环引用”的东西,想知道这是否是问题的一部分(我确实有几个地方 UIViewControllers
被设置为彼此的属性)。感谢您提供任何见解或指向涵盖此内容的引用 Material 。
最佳答案
我会避免养成这种习惯,因为有更好的更安全的选择。使用协议(protocol)/委托(delegate)是 Apple 跨类管理数据的首选方式。您还可以设置 NSNotifications 以将数据/事件从一个类发送/触发到另一个类。 Key Value Observing (KVO) 也是一种很好的监听变化的方式。
在 MVC 结构中, subview 和下游 Controller 真的不应该知道(也就是保留引用)它们的父 View 。它应该始终以相反的方式工作, parent 管理和跟踪 child 。
关于ios - 将 UIViewController 设置为另一个 UIViewController 的属性是不是一个坏主意?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6536158/