如何在iOS开发中保存全局变量? [英] How can I save global variables in iOS development?

查看:539
本文介绍了如何在iOS开发中保存全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个控制器的iOS应用程序,每个控制器都有自己的xib文件。

I have an iOS application with several controllers, each with their own xib files.

如何设置一个跨越所有控制器的范围的全局变量?我应该每次使用 NSUserDefaults 并检索每个视图的数据吗?

How do I set a global variable with scope that spans all controllers? Should I use NSUserDefaults and retrieve data for each view every time?

推荐答案

NSUserDefaults 适用于需要持久性的事物,即您计划在应用程序启动之间存储它们。对于临时变量,请考虑使用单例实例,例如此答案中说明的 MySingleton 类: https://stackoverflow.com/a/145164/108574

NSUserDefaults are for things that require persistance, i.e. you are planning on storing them between app starts. For temporary variables, consider using a singleton instance, such as the MySingleton class illustrated in this answer: https://stackoverflow.com/a/145164/108574 .

当你有这个课时,把您的临时变量为此类的属性,以便于访问。当你需要访问它时,只需调用 [MySingleton sharedSingleton] .variable

When you have this class, put your temporary variables as property of this class for easy access. And when you need to access it, just call [MySingleton sharedSingleton].variable.

同时在此处查看:< a href =http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html =nofollow noreferrer> http://cocoawithlove.com/2008/11/singletons-appdelegates -and-top-level.html 了解更多信息。

Also check here: http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html for more information.

这篇关于如何在iOS开发中保存全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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