保存多个注释-NSUserDefaults

时间:2012-10-04 02:28:58

标签: ios nsuserdefaults mkannotation

我穿过这段代码,如下所示。在下面的代码中,我只能保存一个注释,但是我有一个注释数组,我无法用单个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];

}

1 个答案:

答案 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.

一对夫妇注意到:

  • 如果您不使用ARC,请记住释放alloc'd对象。
  • 这使用新的Objective c对象文字语法和字典访问语法。如果您不使用xcode 4.5,则需要以传统方式构建和访问它们,dictionaryWithObjectsAndKeys:objectForKey: