保留 UIViewController 或不在导航堆栈中
我有一个场景,我不确定是否保留视图控制器。假设我有 ViewControllerOne
。当按下按钮时,ViewControllerOne
会将 ViewControllerTwo
推送到导航堆栈中。 ViewControllerTwo
需要对 ViewControllerOne
的引用,因为它需要访问该视图控制器中的 ivar。问题是,我是否会在 ViewControllerTwo
中保留 ViewControllerOne
(@property (retain) ViewControllerOne *vc
)?导航控制器已经保留了 ViewControllerOne ,所以我不太确定。
谢谢
I have a scenario that I'm not sure whether to retain a view controller or not. Say I had ViewControllerOne
. When a button was pressed, ViewControllerOne
would push ViewControllerTwo
in the navigation stack. ViewControllerTwo
needs a reference to ViewControllerOne
because it needs to access an ivar in that view controller. The question is, would I retain ViewControllerOne
in ViewControllerTwo
(@property (retain) ViewControllerOne *vc
) or not? The navigation controller already retains the ViewControllerOne
so I'm not really sure.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能应该将 viewControllerOne 设置为 viewControllerTwo 的委托。一般情况下,不保留代表。
正如您所描述的,viewControllerTwo 不需要特别了解有关 viewControllerOne 的任何信息,它只需要知道如何访问一段数据并通知更高级别的对象该数据的更改。这是代表的常见角色。
You should probably set viewControllerOne up as a delegate of viewControllerTwo. In general, a delegate is not retained.
As you have described it, viewControllerTwo does not need to know anything about viewControllerOne in particular, it just needs to know how to access a piece of data and inform a higher level object of changes to that data. That is a common role for a delegate.
问题是:为什么
ViewControllerTwo
需要从ViewControllerOne
访问 ivar?更好的方法是在将
ViewControllerTwo
推入堆栈之前,将ViewControllerOne
中的 ivar 值传递给ViewControllerTwo
。The question is: Why does
ViewControllerTwo
need to access an ivar fromViewControllerOne
?The better approach would be to pass the value of the ivar in
ViewControllerOne
toViewControllerTwo
before pushingViewControllerTwo
to the stack.兰普拉戈是正确的。
最好的解决方案是向 ViewControllerTwo 添加一个属性,并将 iVar 从 ViewControllerOne 传递给它,然后再将其推送到导航堆栈。
按照惯例,如果 ViewControllerTwo 是一个对象,则应保留添加到 ViewControllerTwo 的属性,尽管在此示例中您可以使用指定的属性,因为 ViewControllerTwo 将在 ViewControllerOne 之前释放,并且我假设 ViewControllerOne 已保留
ObjectiveC 中的 iVar 所有变量对象通过引用原语传递,结构体通过值传递,就像在 C 中一样
Ranpraygo is correct.
The best solution is to add a property to ViewControllerTwo and pass the iVar from ViewControllerOne to it before pushing it to the navigation stack.
By convention the property added to ViewControllerTwo should be retained if it is an object although you could get away with an assigned property in this example because the ViewControllerTwo will be released before ViewControllerOne is and I assume ViewControllerOne has retained the iVar
In objectiveC all variables that are objects are passed by reference primitives and structs are passed by value as they would be in C