iPhone正确使用应用程序代表 [英] iPhone proper usage of Application Delegate

查看:103
本文介绍了iPhone正确使用应用程序代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在应用程序中的任何地方引用某些状态/对象。例如,用户登录到他们的应用程序,我需要调用Web服务并检索用户信息。然后我想在应用程序的任何地方访问这些信息,如下所示:

  myAppDelegate * delegate = [UIApplication sharedApplication] delegate]; 
user = delegate.u;

在应用程序委托中设置一个实例变量作为User对象,并在需要时引用它差的方式去吗?我通常在用户登录时设置它。



希望了解专业人员如何处理这个。

解决方案

通常情况下,应该只将应用程序代理连接到应用程序委托:




  • 与应用程序委托相同的NIB文件(即单个窗口界面中的静态UI元素)

  • 与通过应用程序委托的应用程序级事件处理相关联窗口)



对于一切,您应该创建一个单例管理对它们的访问。



Jason Coco建议通过应用程序控制器进行路由。在我的程序中,我通常避免这一点,因为我认为它在顶层承担了太多的责任 - 我认为事情应该在可能的情况下自我管理,并且只有当需要协调同级 -



我不会链接我自己的博客,但如果你Google我和单身人士,你可能会找到一个我写的更多细节的帖子。 p>

I'm looking to be able to reference certain state/objects through anywhere in my application. For instance, a user logs in to their application, I need to call a web service and retrieve the users information. Then I want to be able to access this information from anywhere in the application with something like the following:

myAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
user = delegate.u;

Is setting an instance variable as a User object in the app delegate and referencing it from there when needed a poor way of going about it? I typically set it there upon the user's login.

Wanted to hear how the pros handle this one.

解决方案

Normally, you should only connect things to the app delegate if they:

  • Were created from the same NIB file as the app delegate (i.e. static UI elements in single window interfaces)
  • Are associated with application-level event handling that passes through the app delegate (like the menu item for the Preferences Window)

For everything else, you should create a singleton which manages access to them.

Jason Coco suggested routing through the Application Controller. In my programs I normally avoid this, as I think it puts too much responsibility at the top level -- I think things should self-manage where possible and that higher level management should only be used when there is a requirement for coordination between peer-level modules.

I'm not going link my own blog but if you Google me and singletons you'll probably find a post I wrote going into more detail.

这篇关于iPhone正确使用应用程序代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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