awakeFromNib 和局部变量问题
希望我不会因此而受到责备...
有人可以解释一下这是如何将 ManagedObjectContext 传递给 rootViewController 的吗?
以下是为 iOS 核心数据应用自动生成的样板代码:
- (void)awakeFromNib
{
RootViewController *rootViewController = (RootViewController *)
[self.navigationController topViewController];
rootViewController.managedObjectContext = self.managedObjectContext;
}
在此 awakeFromNib
中,rootViewController
是一个局部变量。因此,我认为当方法结束时它会超出范围。我敢打赌这与笔尖在 IB 中的接线方式有关,但我正在寻找更好的解释。如果我注释掉这段代码,应用程序就会崩溃,因为它找不到对象模型。我知道它有效,我只是想知道它为什么以及如何工作。谢谢你!
Hope I don't get chided for this one...
Can someone explain how this passes the managedObjectContext to the rootViewController?
The following is boilerplate code automatically generated for an iOS core data app:
- (void)awakeFromNib
{
RootViewController *rootViewController = (RootViewController *)
[self.navigationController topViewController];
rootViewController.managedObjectContext = self.managedObjectContext;
}
In this awakeFromNib
, rootViewController
is a local variable. Therefore, I thought it would go out of scope when the method ends. I'm betting it has something to do with how the nib is wired in IB, but I'm searching for a better explanation. If I comment out this code, the app crashes because it can't find the object model. I know it works, I would just like to know why and how it works. Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
变量 rootViewController 是一个指向 RootViewController 类型的指针,是的,它是一个局部变量。但它指向的 RootViewController 对象不在本地范围内。正如您所看到的,您通过询问 topViewController 来从 navigationController 获取指针。该对象由 NavigationController 对象保留,因此即使指针超出范围,它仍然存在。无论如何,这不是 Java、C# 或 C++。 Objective-C 中的对象根据引用计数进行释放。
您可能应该更多地了解 Objective C 中的内存管理,以了解更多相关内容。
The variable rootViewController is a pointer to a type RootViewController, and yes it is a local variable. But the object of RootViewController that it points to is not in local-scope. As you can see that you obtain the pointer from the navigationController by asking for it's topViewController. That object is retained by the NavigationController object, so it would still be around even after the pointer goes out of scope. In any case, this is not Java or C# or C++. The objects get deallocated in Objective-C based on reference counting.
You should probably understand more about Memory Management in Objective C to learn more about this.