Archiving a CLLocation

Discussion in 'iOS Programming' started by nixesmixes, Jun 4, 2010.

  1. nixesmixes macrumors newbie

    Feb 4, 2010
    I have a class called MapPoint which represents an MKAnnotation on a MapView. I want to archive the MapPoint so it can persist. I am having trouble figuring out how to archive a structure (specifically CLLocationCoordinate2D) using the method - (void)encodeWithCoder:(NSCoder *)encoder. The documentation says that you cannot encode structures and need to pull out each variable within the structure that you want to archive. The CLLocationCoordinate2D is a structure that takes this form:

    typedef struct {
    CLLocationDegrees latitude;
    CLLocationDegrees longitude;
    } CLLocationCoordinate2D;

    CLLocationDegrees is of the form:

    typedef double CLLocationDegrees

    It appears I need to put latitude and longitude each into a float variable and archive them that way.

    Any help as to how I would go about doing this would be extremely helpful.

    Thank you!!!
  2. Luke Redpath macrumors 6502a

    Nov 9, 2007
    Colchester, UK
    Create instances of NSNumber using numberWithDouble: and archive those.
  3. Thomas Harte macrumors 6502

    Nov 30, 2005
    You're overcomplicating things. CLLocation isn't a property list value so you can't directly archive it, but it does respond to NSCoding, which is the protocol that a class implements when it can archive and unarchive itself.

    So, e.g.

    CLLocation *location = ...
    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:location] forKey:@"someKey"];
    Will do. And because you're using the proper protocol and devolving the task to the object as per proper design principles, you can immediately do things like:

    CLLocation *location1 = ...
    CLLocation *location2 = ...
    NSArray *arrayOfLocations = [NSArray arrayWithObjects:location1, location2, nil];
    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:arrayOfLocations] forKey:@"someKey"];
    Which will, as it says, archive the entire array.

    EDIT: actually, a good learning point. Implement NSCoding in your own classes (and have them call the relevant encode or decode method on their instance variable objects) and you can archive your entire data structure from just the single root object, if you have one.

Share This Page