3

My iOS application needs to store an MKPolyline inside of an NSUserDefault. I've been doing a lot of research, and I now know that:

  • NSUserDefaults are a subclass of NSCoder
  • MKPolyline is not a subclass of NSCoder

As a result, it is rather difficult to save a polyline to . I have attempted to convert the MKPolyline into NSData:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:routeLine]; // routeLine is an MKPolyline
[defaults dataForKey:@"key"];
[defaults synchronize];

When I try to convert the polyline to NSData, I get this error message:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MKPolyline encodeWithCoder:]: unrecognized selector sent to instance 0xba1fd70

I can successfully perform the above code when using an MKPolylineView however then I have issues getting the MKPolyline back out of the View. I found this Q/A on SO but it doesn't solve my issue because it would change the way my app functions.

How can I save an MKPolyline? Can I subclass it, if so what would that entail? Or is there a way to do it with the MKPolylineView? Am I missing something with NSCoder?

Community
  • 1
  • 1
Sam Spencer
  • 8,492
  • 12
  • 76
  • 133

1 Answers1

4

While you can implement NSCoding yourself for MKPolyline, and then construct an NSData representation and store that in NSUserDefaults, it might be better to represent the MKPolyline using arrays and dictionaries, which NSUserDefaults can directly handle.

Construct an array of dictionaries which encapsulate the x and y values for each point, and store that in NSUserDefaults instead of the MKPolyline.

When loading defaults, get the array, loop through the dictionaries reconstructing the points, and then re-create the MKPolyline.

DD_
  • 7,230
  • 11
  • 38
  • 59
paulmelnikow
  • 16,895
  • 8
  • 63
  • 114