本文介绍了Objective-C单例对象和全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有关这个主题的其他帖子,但我只是真的一个梯子从一个noob,所以需要一些更多的帮助。

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.

我的iPhone应用程序有几个全局变量 - 一些我已经声明和给一个类中的值,但其他人需要在登录过程中设置(例如一个令牌),然后需要从任何类的应用程序的生命周期或方法。我被告知,我真的应该使用一个Singleton对象的所有这一切,我假设是一个类,启动时实例化。如果是这样,有人可以给我最简单的例子这样的头和实现文件和如何/我应该实例化它?然后我需要一些字符串设置从关闭和其他可以设置/稍后开始?

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. 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. 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.

谢谢,

推荐答案

此链接显示一些代码来创建单例类:

This link shows some code to create a singleton class : http://www.galloway.me.uk/tutorials/singleton-classes/

您可以使用它: / p>

You would use it something like :

[[MyManager sharedManager] doSomething];

对sharedManager的调用将获得类的一个实例(或者,如果这是第一次你调用它,会创建它) - 这确保你只有其中一个:)

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 :)

它还覆盖release,retain,autorelease等,以确保你不能意外地摆脱sharedManager的错误!

It also overrides release, retain, autorelease etc to make sure that you can't accidentally get rid of the sharedManager by mistake!

这个类将实例化自己第一次使用它,但如果你需要它在启动时创建,只是

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.

你可以像任何其他的目标定义类一样定义类, c类 - 只需添加属性等

You define the class like any other objective-c class - just add properties etc

希望有助于:)

这篇关于Objective-C单例对象和全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 19:11