我尝试在NSMutableArray
中添加NSUserDefault
,但它总是重新调整为空。
我知道。所以我甚至创建了一个可变复制的os数组,但仍然。
NSUserDefaults返回的值 即使你设置了一个,也是不可变的 可变对象作为值。对于 例如,如果您设置了一个可变字符串 作为" MyStringDefault"的值, 您稍后使用的字符串 stringForKey:将是不可变的。
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *myStoredEvents=[prefs objectForKey:@"MySavedEvents"];
NSMutableArray *myStoredEventsNew=[[NSMutableArray alloc]init];
myStoredEventsNew=myStoredEvents;
NSMutableArray *tempDic=[myevents objectAtIndex:eventId];//myevents a NSMutableArray
if(myStoredEventsNew != nil)
{
[myStoredEventsNew insertObject:tempDic atIndex:0];
}
else
{
[myStoredEventsNew insertObject:tempDic atIndex:myStoredEvents.count];
}
NSLog(@"New dictonary before modification :%@",tempDic);
[prefs setObject:myStoredEventsNew forKey:@"MySavedEvents"];
[prefs synchronize];
答案 0 :(得分:0)
试试这段代码 -
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(@"DEBUG :: %@",[prefs objectForKey:@"MySavedEvents"]);
NSMutableArray *myStoredEvents;
if ([prefs objectForKey:@"MySavedEvents"] == NULL) {
myStoredEvents = [[NSMutableArray alloc]init];
}else{
myStoredEvents=[[prefs objectForKey:@"MySavedEvents"] mutableCopy];
}
NSMutableArray *tempDic=[myevents objectAtIndex:eventId];//myevents a NSMutableArray
[myStoredEvents addObject:tempDic];
NSLog(@"New dictonary before modification :%@",myStoredEvents);
[prefs setObject:myStoredEvents forKey:@"MySavedEvents"];
[prefs synchronize];
这可以解决你的问题
答案 1 :(得分:0)
您可以在NSuserdefaults中保存数组,如下所示: -
[[NSUserDefaults standardUserDefaults] setObject:yourArray forKey:@"MySavedEvents"];
[[NSUserDefaults standardUserDefaults] synchronize];
您可以将检查条件设置为检查NSuserdefault,如下所示: -
NSObject * object = [prefs objectForKey:@"MySavedEvents"];
if(object != nil){
//object is there
}
您可以根据需要提出更多条件,这只是如何实现这一目标的基本结构。