[英]NSUserDefaults returning (null)
I'm a newcomer to NSUserDefaults
and am struggling to get my head around something I imagine is probably straightforward for most reading this. 我是
NSUserDefaults
的新手,正在努力让我NSUserDefaults
我认为对于大多数阅读本书而言直截了当的事情。
I'm trying to retrieve a mutable array of strings if it exists in NSUserDefaults
with the following code: 我正在尝试使用以下代码检索
NSUserDefaults
存在的可变字符串数组:
NSMutableArray *globalAppsArray;
if([[NSUserDefaults standardUserDefaults] objectForKey:@"globalAppsArray"] != nil)
{
NSLog(@"Array found. Contents: %@", globalAppsArray);
}
else
{
globalAppsArray = [[NSMutableArray alloc] initWithCapacity:0];
}
After adding any new data to it I then want to save it: 向其中添加任何新数据后,我想保存它:
[[NSUserDefaults standardUserDefaults] setObject:globalAppsArray forKey:@"globalAppsArray"];
[[NSUserDefaults standardUserDefaults] synchronize];
When I relaunch the app, the mutable array is found OK but the contents are null
. 当我重新启动该应用程序时,该可变数组确定为OK,但是内容为
null
。
Can someone tell me what I'm missing? 有人可以告诉我我所缺少的吗?
It should be something like this: 应该是这样的:
NSMutableArray *globalAppsArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"globalAppsArray"];
if(globalAppsArray != nil)
{
NSLog(@"Array found. Contents: %@", globalAppsArray);
}
else
{
globalAppsArray = [[NSMutableArray alloc] initWithCapacity:0];
}
check your code once, 一次检查您的代码,
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *globalAppsArray = [[defaults objectForKey:@"globalAppsArray"] mutableCopy];
if(globalAppsArray)
NSLog(@"Array found. Contents: %@", globalAppsArray);
else
globalAppsArray = [NSMutableArray array];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.