【发布时间】:2011-08-14 19:57:09
【问题描述】:
我必须在我的程序中使用 NSDate var,并且该 var 将是 dealloc 和 realloc(我必须在该日期添加一些月份和年份,并且没有其他可能性)。
该 var 在许多方法中必须是用户,我想将此 var 放在全局中。还有其他选择吗?不干净,但我不知道该怎么做...
非常感谢帮助我!!!
【问题讨论】:
标签: iphone objective-c xcode global-variables nsdate
我必须在我的程序中使用 NSDate var,并且该 var 将是 dealloc 和 realloc(我必须在该日期添加一些月份和年份,并且没有其他可能性)。
该 var 在许多方法中必须是用户,我想将此 var 放在全局中。还有其他选择吗?不干净,但我不知道该怎么做...
非常感谢帮助我!!!
【问题讨论】:
标签: iphone objective-c xcode global-variables nsdate
我建议将其放入您的 AppDelegate。然后你可以通过
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"%@", [appDelegate myGlobalDate]);
当然,您需要在 MyAppDelegate 中为 myGlobalDate 设置 getter 和 setter。
【讨论】:
想想这个变量的用途,以及你最常使用它的地方。那么你应该已经为它找到了一个自然的地方。
全局变量不是绝对可怕的东西,单例也不是(可能很适合这里)。但是,也许它真的属于用户默认值,或者某个视图控制器。
【讨论】:
回答是否有其他选择的问题(而不是说是否应该这样做)。一种选择是专门创建一个类作为保存您需要全局可用的变量的地方。来自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 模式。
【讨论】: