Search code examples
iphoneiosobjective-cnsuserdefaultscllocationmanager

Store CLLocationCoordinate2D to NSUserDefaults


I am new to iphone development, and i want to store CLLocationCoordinate2D object to NSUserDefaults. I am Trying

    [defaults setObject:location forKey:@"userLocation"];

But it gives error 'Sending CLLocationCoordinate2D to parameter of incompatible type id'

So How to store CLLocationCoordinate2D into NSUserDefaults? Thanks.


Solution

  • As pdrcabrod said,

    "A default object must be a property list, that is, an instance of NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary."

    I use this to store,

        NSNumber *lat = [NSNumber numberWithDouble:location.latitude];
        NSNumber *lon = [NSNumber numberWithDouble:location.longitude];
        NSDictionary *userLocation=@{@"lat":lat,@"long":lon};
    
        [[NSUserDefaults standardUserDefaults] setObject:userLocation forKey:@"userLocation"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    

    And access using,

        NSDictionary *userLoc=[[NSUserDefaults standardUserDefaults] objectForKey:@"userLocation"];
        NSLog(@"lat %@",[userLoc objectForKey:@"lat"]);
        NSLog(@"long %@",[userLoc objectForKey:@"long"]);