Save MKPolyline as NSData in NSUserDefaults
My iOS app needs to store MKPolyline
internally NSUserDefault
. I've done a lot of research and now I know that:
- NSUserDefaults are a subclass of NSCoder
- MKPolyline is not a subclass of NSCoder
As a result, it is rather difficult to keep the polyline in nsuserdefaults... I tried to convert MKPolyline to NSData:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:routeLine]; // routeLine is an MKPolyline
[defaults dataForKey:@"key"];
[defaults synchronize];
When I try to convert polyline to NSData I get this error message:
Application terminated due to uncaught exception "NSInvalidArgumentException", reason: '- [MKPolyline encodeWithCoder:]: unrecognized selector sent to instance 0xba1fd70
I can successfully execute the above code when using MKPolylineView , but then I have problems returning MKPolyline from view. I found this Q / A on SO but it doesn't solve my problem because it will change the way my application works.
How to save MKPolyline? Can I subclass it, if so what will it entail? Or is there a way to do this using MKPolylineView? Am I missing something with NSCoder?
source to share
As long as you can implement NSCoding
yourself for MKPolyline
, and then build a view NSData
and store it in NSUserDefaults
, it would be better to represent MKPolyline
using arrays and dictionaries that NSUserDefaults
can directly handle.
Create an array of dictionaries that encapsulate the x and y values for each point and store that in NSUserDefaults
instead MKPolyline
.
When loading defaults, get an array, loop through the dictionaries, recovering points, then re-create MKPolyline
.
source to share