2011-04-28 43 views
1

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

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

非常感谢您的帮助!

回答

1

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

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

当然,你需要getter和setter myGlobalDate在MyAppDelegate。

+1

我反对这种做法。不要让应用程序委托成为“主超级管理员”类。在那里,做到了,从中吸取了教训。 :) – Eiko 2011-04-28 15:43:52

+1

不要让你的应用程序代表乱七八糟。 – Till 2011-04-28 15:44:37

+2

好的,请让我们知道你从这个错误中学到了什么。 – dasdom 2011-04-28 15:45:05

1

想想这个变量有什么用途,以及最经常使用它的地方。那么你应该找到一个自然的地方。

全局变量并不是绝对可怕的,也不是单身人士(其中可能在这里很合适)。但是,可能它确实属于用户默认设置或某个视图控制器。

+0

感谢您指出它。 – dasdom 2011-04-28 15:50:40

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模式,我自己。