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 f开发者_JS百科or 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.
Thanks,
This link shows some code to create a singleton class : 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 :)
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.
You define the class like any other objective-c class - just add properties etc
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.
精彩评论