我正在尝试将CLLocation
数据保存在 Core Data 中。我的属性设置为可转换对象。
那里的一些示例代码表明可以使用转换为NSValue
.
CLLocationCoordinate2D myLocation;
NSValue *locationValue = [NSValue valueWithBytes:&myLocation objCType:@encode(CLLocationCoordinate2D)]
// then put locationValue into storage - maybe an ObjC collection class or core data etc.
从数据存储中检索对象应该使用此范例。
CLLocationCoordinate2D myLocation;
NSValue *locationValue = // restored from your database or retrieved from your collection class
[locationValue getValue:&myLocation];
我试图推断这个想法并将整个CLLocation
对象捕获到一个NSValue
存储中,目标是稍后从存储中CoreData
恢复对象。CLLocation
在测试各种方法时,我发现在尝试CLLocation
从核心数据存储中解包对象时返回了 nil。我正在CLLocation
使用以下方法将对象放入商店:
//verified that I have a good CLLocation here
newManagedObject.setValue(location as CLLocation, forKey: "location")
后来我尝试解开CLLocation
let location = detail.valueForKey("location")! as CLLocation
但我发现该对象没有正确展开。
展开的对象如下所示:
(CLLocation) location = 0x00007fff59537c90 {
ObjectiveC.NSObject = {}
}
CLLocation
所以此时对该对象的任何使用都会返回“ found nil...error ”
我是否遗漏了一些关于CLLocation
使用 Swift 存储/检索对象的明显内容?
更新
Daniel 的回答帮助我意识到 NSValueTransformer 对我不起作用,所以我回到了我以前使用过的方法。基本上使用 NSKeyedArchiver 对对象图进行编码。一如既往,我的目标是使用最简单的解决方案,因此我选择不使用托管对象子类,因为我需要的属性已经在现有的 CLLocation 对象中。我将可转换字段更改为二进制数据,并选中了选项(存储在外部记录文件中)。我开始对主详细信息模板进行最小更改来测试此过程。
保存 CLLocation 对象图
//assuming location is a valid CLLocation and data model has a binary data field
let archivedLocation = NSKeyedArchiver.archivedDataWithRootObject(location)
newManagedObject.setValue(archivedLocation, forKey: "location")
从数据存储中恢复对象图
在主 vc 上,作为默认准备 segue 的一部分,数据通过 fetch 控制器恢复。
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
let controller = (segue.destinationViewController as UINavigationController).topViewController as DetailViewController
controller.detailItem = object
在细节 vc 上,我使用 NSKeyedUnarchiver 解开我的对象图
var lc = NSKeyedUnarchiver.unarchiveObjectWithData(detail.valueForKey!("location") as NSData) as CLLocation