static var or AppDelegate
I have to use a NSDate var in my program开发者_Python百科, and that var will be dealloc and realloc (I must add some month and year to this date and there is no other possibilities).
That var has to be user in many methods and I want to put this var in global. Is there any other options? It's not clean but I don't know how to do in an other way...
Thanks a lot to help me !!!
I would recommend to put it into your AppDelegate. Then you can get it via
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"%@", [appDelegate myGlobalDate]);
Of course then you need getter and setter for myGlobalDate in MyAppDelegate.
Think about what purpose the variable has, and where you use it most often. Then you should have found a natural place for it.
Global variables are not something absolutely terrible, nor are singletons (which might be a good fit here). But then, maybe it really belongs to the user defaults, or a certain view controller.
In answer to the question about whether there are other options (and not speaking to the point of whether one should do this). One option is to make a class specifically as a place to keep variables that you need to have available globally. One example from this blog post
@interface VariableStore : NSObject
{
// Place any "global" variables here
}
// message from which our instance is obtained
+ (VariableStore *)sharedInstance;
@end
@implementation VariableStore
+ (VariableStore *)sharedInstance
{
// the instance of this class is stored here
static VariableStore *myInstance = nil;
// check to see if an instance already exists
if (nil == myInstance) {
myInstance = [[[self class] alloc] init];
// initialize variables here
}
// return the instance of this class
return myInstance;
}
@end
Then, from elsewhere:
[[VariableStore sharedInstance] variableName]
Of course, if you don't like the way they instantiate the singleton in the above example, you can choose your favorite pattern from here. I like the dispatch_once pattern, myself.
精彩评论