Search code examples
iosnsuserdefaultsmkannotation

Saving Multiple Annotations -NSUserDefaults


I came cross this code as shown below.In the following code, I could able to save only one single annotation, however I have an array of annotations, I could not able to save them with single 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];

Edited:

 -(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];

}

Solution

  • As you already have an array, simply use setObject:forKey: and arrayForKey:

    As the objects in your original array are not a type that can be saved directly, store their data in dictionaries:

    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"];
    

    and convert on retrieval:

    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.
    

    A couple notes:

    • If you're not using ARC, remember to release the alloc'd objects.
    • This uses the new objective c object literal syntax and dictionary access syntax. If you aren't using xcode 4.5 you'll need to construct and access them the traditional way, dictionaryWithObjectsAndKeys: and objectForKey: