简体   繁体   English

Objective-C单例对象和全局变量

[英]Objective-C Singleton Objects and Global Variables

I'm aware of other posts on this topic but I'm only really one rung up the ladder from being a noob so need a bit more help. 我知道有关此主题的其他文章,但实际上我只是一个菜鸟而已,因此需要更多帮助。

My iPhone app has several global variables - some I have declared and given values in a class but others need to be set during a login process (like a token for example) that then need to be accessible for the lifecycle of the app from any class or method. 我的iPhone应用程序有几个全局变量-我已经在一个类中声明并给定了值,但其他一些变量则需要在登录过程中设置(例如令牌),然后才能在任何类的应用程序生命周期中对其进行访问或方法。 I am told I should really be using a Singleton object for all of this which I presume is a class that's instantiated on startup. 有人告诉我我真的应该对所有这些都使用Singleton对象,我认为这是在启动时实例化的类。 If so, could someone give me the simplest example of such header and implementation file and how/where I should instantiate it? 如果是这样,有人可以给我最简单的此类标头和实现文件示例,以及如何/在何处实例化它? Then I need to have some strings that are set from the off and others that can be set/got later on? 然后,我需要从关闭处设置一些字符串,然后再设置/获取其他字符串?

Thanks very much in advance. 首先十分感谢。 Also, I'm new here so if my etiquette is off in any way, please let me know. 另外,我是新来的人,因此,如果我的礼节有所不同,请告诉我。

Thanks, 谢谢,

This link shows some code to create a singleton class : http://www.galloway.me.uk/tutorials/singleton-classes/ 此链接显示了创建单例类的一些代码: http : //www.galloway.me.uk/tutorials/singleton-classes/

You would use it something like : 您将使用类似:

[[MyManager sharedManager] doSomething];

The call to sharedManager would get the one instance of the class (or, if this is the first time you called it, would create it) - this makes sure that you only have one of them :) 对sharedManager的调用将获得该类的一个实例(或者,如果这是您第一次调用该类,则将创建它)-确保您只有一个实例:)

It also overrides release, retain, autorelease etc to make sure that you can't accidentally get rid of the sharedManager by mistake! 它还覆盖释放,保留,自动释放等功能,以确保您不会意外地误删除sharedManager!

This class will instantiate itself the first time you use it but if you need it to be created on startup, just call [MyManager sharedManager] and it will create it for you. 此类在首次使用时将实例化自己,但是如果需要在启动时创建它,只需调用[MyManager sharedManager] ,它将为您创建它。

You define the class like any other objective-c class - just add properties etc 您可以像定义任何其他Objective-C类一样定义类-只需添加属性等

Hope that helps :) 希望有帮助:)

Global variables aren't good, but singletons aren't much better when they're just used to provide global access to some data. 全局变量不是很好,但是当单例仅用于提供对某些数据的全局访问时,它们并不会好得多。 Anything bad you can say about a global variable, you can also say about a singleton that's used for global access. 关于全局变量,您可以说的不好,也可以用于全局访问的单例。 A better solution is to create a data model and pass that model from one view controller to the next. 更好的解决方案是创建一个数据模型,并将该模型从一个视图控制器传递到下一个视图控制器。

Here's a previous SO question that might help. 这是一个先前的SO问题 ,可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM