Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

nixesmixes

macrumors newbie
Original poster
Feb 4, 2010
11
0
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!!!
 

Thomas Harte

macrumors 6502
Nov 30, 2005
400
4
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.

Code:
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:

Code:
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.