serDefaults中将MKPolyline保存为NSData

serDefaults中将MKPolyline保存为NSData

本文介绍了在NSUserDefaults中将MKPolyline保存为NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的iOS应用程序需要在 NSUserDefault 中存储 MKPolyline 。我一直在做很多研究,现在我知道:

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是NSCoder的子类

  • MKPolyline不是NSCoder的子类

因此,将折线保存到 nsuserdefaults 。我试图将MKPolyline转换为NSData:

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];

当我尝试将折线转换为NSData时,收到以下错误消息:

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

我在使用 MKPolylineView 时可以成功执行上述代码,但是我遇到了将MKPolyline从View中取回的问题。我发现了,但它没有解决我的问题,因为它会改变我的应用程序的运行方式。

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.

如何保存MKPolyline?我可以将其子类化,如果是这样的话会带来什么?或者有没有办法用MKPolylineView做到这一点?我错过了NSCoder的东西吗?

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?

推荐答案

虽然你可以实现 NSCoding 你自己 MKPolyline ,然后构建一个 NSData 表示并将其存储在 NSUserDefaults ,使用数组和字典表示 MKPolyline 可能更好, NSUserDefaults 可以直接处理。

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.

构造一个字典数组,封装每个点的x和y值,并将 存储在 NSUserDefaults 而不是 MKPolyline

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

加载默认值时,获取数组,循环遍历字典重建点,然后重新创建 MKPolyline

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

这篇关于在NSUserDefaults中将MKPolyline保存为NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:53