Save MKPolyline as NSData in NSUserDefaults

こ雲淡風輕ζ 提交于 2019-12-02 00:25:25

问题


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 nsuserdefaults. 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?


回答1:


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.



来源:https://stackoverflow.com/questions/14927915/save-mkpolyline-as-nsdata-in-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!