在视图层次结构中组织实例变量 [英] Organizing instance variables in a view hierarchy

查看:143
本文介绍了在视图层次结构中组织实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当为iPhone编程时,我发现我经常需要在多个视图中使用相同的对象实例。什么是最好的办法呢?到目前为止,我的策略是将其创建为根视图的成员,并将其传递给后续视图,将其保留为成员。然而,这似乎不是一个很好的方法,因为很难更新每个类中引用的引用。我也看过单身班以及AppDelegate用于这个目的。作为iPhone开发人员,您如何处理大型应用程序中的这个问题?

解决方案

App Delegate方法很容易做到,不幸的是,一切都必须去取得代理,然后获取共享的对象。



单例意味着只有使用单例的类必须知道它,但可能更难在低内存情况下对单元测试或正确清理。此外,您还必须更仔细地编写单身课程,以便他们能够正常工作(请看单独的Apple文档)。



传递一个对象可能会变老,因为有时候你只会结束有一个链接到对象传递给别人,所以我会避免这种方法,除非你只是从一个父母传递给几个直接的孩子。



在第一个由于依赖关系图更简单,所以我倾向于单身人士(因为所提到的类只包括他们关心的单例头,而不是应用程序代表的一大堆)。如果你有一些他们要做的事情是将单独的分配类放在单个类的单个实例上,只是为了使应用程序委托更轻,不必使这么多类是真正的单例。 / p>

我喜欢使用应用程序委托来保持实际UI的根目录,如标签栏控制器或主视图控制器。这似乎比其他地方更自然。


When programming for the iPhone, I find that I often need to use the same instance of an object in multiple views. What is the best way to handle this? My strategy so far has been to create it as a member of the root view and pass it to subsequent views which retain it as a member. However, this does not seem like a very good approach since it would be very difficult to update what the reference in each class is pointing to. I have also seen singleton classes as well as the AppDelegate used for this purpose. As an iPhone developer, how do you handle this problem in large apps?

解决方案

The App Delegate approach is easy to do, the downside is that everything has to go fetch the delegate and then get the shared object.

Singletons mean only classes using the singleton have to know about it, but can be harder to write unit tests against or clean up properly in low memory situations. Also you must write the singleton classes more carefully so they work correctly (look at Apple docs on singletons).

Passing an object around can get old because sometimes you end up only having a link to the object to pass to someone else, so I would avoid that approach unless you were just passing from one parent to a few immediate children.

Between the first two, I lean a little towards singletons just because of the dependency graph being simpler (as mentioned classes only including singleton headers they care about instead of a whole bunch from the App Delegate). If you had a number of them the thing to do would be to make singleton distribution classes that held onto single instances of groups of classes, just to keep the app delegate lighter and not to have to make so many classes that were true singletons.

I do like using the app delegate to hold on to the root of your actual UI, like the tab bar controller or primary view controller. That just seems more natural than stuffing it elsewhere.

这篇关于在视图层次结构中组织实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆