创建一个变量,该变量最终将保存所有方法使用的一段数据 [英] Creating a variable that will eventually hold a piece of data to be used by all methods
问题描述
我是 Objective-c 的新手,我只是想知道我将如何去做?我会创建一个常量并简单地填充它吗?
I am new to objective-c and I was just wondering how would I go about doing this? Would I create a constant and simply fill it?
示例
我有一个 NSString *date.我从互联网上获取了一些数据,现在我在这个变量中得到了我想要的日期.我希望能够随时使用此 NSString,而无需调用在我的程序中的任何范围内返回它的方法.
I have a NSString *date. I fetch some data from the internet and now I have the date I want in this variable. I want to be able to use this NSString at anytime without calling a method that returns it at any scope within my program.
提前致谢!
决定使用基于答案的单例...
Decided to use singletons based on answer...
我应该把代码放在哪里来从互联网上检索变量将保存的日期?会在这里吗?
Where would I put the code to retrieve the date from the internet that the variable will hold? Would it be here?
static SingletonClass *sharedInstance = nil;
// Get the shared instance and create it if necessary.
+ (SingletonClass *)sharedInstance {
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
}
//Put Code here??
return sharedInstance;
}
推荐答案
如果您所做的只是存储单个日期变量,我建议使用 NSUserDefaults.如果您使用单例,则无论如何您都必须在启动之间保留数据.和 NSUserDefaults 是一个单例.如果您创建一个单例,那么您将创建另一个类等等.
if all your doing is storing a single date variable, I would suggest using NSUserDefaults. if you use a singleton then you'll have to persist the data between launches anyways. and NSUserDefaults is a singleton. If you create a singleton then you'll to create another class and so forth.
存储:
NSDate *updateDate = [NSDate date];
[[NSUserDefaults standardUserDefaults] updateDate forKey:@"lastUpdateDate"];
[[NSUserDefaults standardUserDefaults] synchronize];
检索:
NSDate *updateDate = [[NSUserDefaults standardUserDefaults] dateForKey:@"lastUpdateDate"];
这篇关于创建一个变量,该变量最终将保存所有方法使用的一段数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!