我穿过这段代码,如下所示。在下面的代码中,我只能保存一个注释,但是我有一个注释数组,我无法用单个NSUserDefaults保存它们
To save:
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
[ud setDouble:location.latitude forKey:@"savedCoordinate-latitude"];
[ud setDouble:location.longitude forKey:@"savedCoordinate-longitude"];
[ud setBool:YES forKey:@"savedCoordinate-exists"];
[ud synchronize];
编辑:
-(void)viewDidLoad
NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
if([ud boolForKey:@"save-exist"])
{ NSMutableArray *udAnnotations=[[NSMutableArray alloc]initWithArray:
[ud objectForKey:@"annotationsArray"]];
NSLog(@"%d",[udAnnotations count]);
}
else{
[self addAnno];
}
-(void)addAnno
{
[mapView addAnnotations:annotationArray];
NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
[ud setObject:annotationArray forKey:@"annotationsArray"];
[ud setBool:YES forKey:@"save-exist"];
[ud synchronize];
}
答案 0 :(得分:1)
由于您已有数组,只需使用setObject:forKey:
和arrayForKey:
由于原始数组中的对象不是可以直接保存的类型,请将其数据存储在词典中:
NSMutableArray *saveData = [[NSMutableArray alloc] initWithCapacity:originalData.count];
for(id location in originalData) {
[saveData addObject:@{@"lat":[location latitude], @"lon":[location longitude]}];
}
[[NSUserDefaults standardUserDefaults] setObject:saveData forKey:@"annotationsArray"];
并转换检索:
NSMutableArray *restoredData = [[NSMutableArray alloc] init];
for(NSDictionary *data in [[NSUserDefaults standardUserDefaults] arrayForKey:@"annotationsArray"]) {
[restoredData addObject:[[Location alloc] initWithLat:data[@"lat"] andLon:data[@"lon"]]];
}
// if restoredData.count is 0, there were no stored objects.
一对夫妇注意到:
dictionaryWithObjectsAndKeys:
和objectForKey: