NSUserDefaults:有关两种方法之间差异的问题
问题
我想在 NSUserDefaults 中存储 NSString 并稍后检索它。我对两种不同的检索方法有疑问。现在,在文件顶部我有:
// String used to identify the update object in the user defaults storage.
static NSString * const kLastStoreUpdateKey = @"LastStoreUpdate";
方法 1
NSString *lastUpdate = [[NSUserDefaults standardUserDefaults] objectForKey:kLastStoreUpdateKey];
方法 2
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = [prefs stringForKey:kLastStoreUpdateKey];
是否存在我应该了解的显着差异?另外,有人可以解释一下 objectForKey
到底是什么吗? Apple 的 API 声明:它“返回与第一次出现的指定默认值关联的对象。”“指定默认值”到底是什么意思?
谢谢!
Problem
I want to store a NSString in NSUserDefaults and retrieve it later. I have a question about two different retrieving methods. Now at the top of the file I have:
// String used to identify the update object in the user defaults storage.
static NSString * const kLastStoreUpdateKey = @"LastStoreUpdate";
Method 1
NSString *lastUpdate = [[NSUserDefaults standardUserDefaults] objectForKey:kLastStoreUpdateKey];
Method 2
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = [prefs stringForKey:kLastStoreUpdateKey];
Are there are significant differences I should know about? Also, can someone please explain what exactly is objectForKey
? Apple's API states: that it "Returns the object associated with the first occurrence of the specified default." What exactly do they mean by the "specified default?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,您应该使用方法1,
即“objectForKey”。
因为,你知道,无论你在 NSUserDefault 中存储了什么。因此,在检索它时,您可以使用适当的类(如 NSString、Array 或任何其他用户定义的类)捕获该对象。
通常不使用“stringForKey”。
如果您将 ingteger、BOOL 存储到 NSUserDefault 中,那么您应该使用 intForKey、BOOLforKey 等。
干杯。
Generally you should use method 1.
that is "objectForKey".
Because, you know that, whatever you have stored in NSUserDefault. So, at the time of retriving it, you can catch the object with proper class like NSString, Array or any other user defined.
genrally "stringForKey" is not used.
If you are storing ingteger, BOOL into NSUserDefault then you should use intForKey, BOOLforKey, etc..
Cheers.