static var或AppDelegate

时间:2011-04-28 15:27:08

标签: iphone objective-c xcode global-variables nsdate

我必须在我的程序中使用NSDate var,并且var将是dealloc和realloc(我必须在此日期添加一些月份和年份,并且没有其他可能性。)

var必须是许多方法的用户,我想把这个var放在全局。还有其他选择吗?它不干净,但我不知道如何以其他方式做...

非常感谢帮助我!!!

3 个答案:

答案 0 :(得分:1)

我建议把它放到AppDelegate中。然后你可以通过

获得它
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"%@", [appDelegate myGlobalDate]);

当然,你需要在MyAppDelegate中为myGlobalDate设置getter和setter。

答案 1 :(得分:1)

考虑变量的用途,以及最常使用的位置。那么你应该找到一个自然的地方。

全局变量并非绝对可怕,单身人士(可能非常适合这里)。但是,它可能真的属于用户默认值或某个视图控制器。

答案 2 :(得分:1)

回答有关是否有其他选择的问题(而不是说是否应该这样做)。一种选择是将类专门用作保存全局可用变量的位置。这个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

然后,来自其他地方:

[[VariableStore sharedInstance] variableName]

当然,如果你不喜欢他们在上面的例子中实例化单身人士的方式,你可以选择自己喜欢的pattern from here。我喜欢dispatch_once模式,我自己。