core-data - 在 CoreData 中保存 Swift CLLocation

标签 core-data swift cllocation nsvalue

我试图在 Core Data 中保存 CLLocation 数据。我的属性设置为 Transformable 对象。

那里的一些示例代码表明可以使用转换为 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 对象捕获到存储在 CoreData 中的 NSValue 中,目的是恢复稍后从商店中获取 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

展开的对象看起来像:

(CLLocation) location = 0x00007fff59537c90 {
  ObjectiveC.NSObject = {}
}

因此此时对 CLLocation 对象的任何使用都会返回“found nil... error

我是否遗漏了一些关于使用 Swift 存储/检索 CLLocation 对象的明显信息?

更新

Daniel 的回答让我意识到 NSValueTransformer 对我不起作用,所以我又回到了以前使用过的方法。基本上使用 NSKeyedArchiver 对对象图进行编码。一如既往,我的目标是使用尽可能简单的解决方案,因此我选择不使用托管对象子类,因为我需要的属性已经存在于现有的 CLLocation 对象中。我将可转换字段更改为二进制数据,并选中了选项(存储在外部记录文件中)。我着手测试这个过程,对主细节模板进行最少的更改。

data-model

保存 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 上,作为默认 prepare for segue 的一部分,数据通过获取 Controller 恢复。

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

最佳答案

当你为 CLLocation 对象创建一个 NSManagedObject 子类时,你会遇到更少的麻烦。然后创建存储和检索方便的方法:

import Foundation
import CoreData
import CoreLocation

class LocationPoint: NSManagedObject {

    @NSManaged var latitude: NSNumber!
    @NSManaged var longitude: NSNumber!
    @NSManaged var altitude: NSNumber!
    @NSManaged var timestamp: NSDate!
    @NSManaged var horizontalAccuracy: NSNumber
    @NSManaged var verticalAccuracy: NSNumber
    @NSManaged var speed: NSNumber
    @NSManaged var course: NSNumber

    func initFromLocation(location: CLLocation) {
        self.latitude           = location.coordinate.latitude
        self.longitude          = location.coordinate.longitude
        self.altitude           = location.altitude
        self.timestamp          = location.timestamp

        self.horizontalAccuracy = location.horizontalAccuracy > 0.0 ? location.horizontalAccuracy : 0.0
        self.verticalAccuracy   = location.verticalAccuracy > 0.0 ? location.verticalAccuracy : 0.0
        self.speed              = location.speed > 0.0 ? location.speed : 0.0
        self.course             = location.course > 0.0 ? location.course : 0.0
    }

    func location() -> CLLocation {
        return CLLocation(
            coordinate: CLLocationCoordinate2D(latitude: self.latitude.doubleValue, longitude: self.longitude.doubleValue),
            altitude: self.altitude.doubleValue,
            horizontalAccuracy: self.horizontalAccuracy.doubleValue,
            verticalAccuracy: self.verticalAccuracy.doubleValue,
            course: self.course.doubleValue,
            speed: self.speed.doubleValue,
            timestamp: self.timestamp
        )
    }

您必须根据此类使用实体设置数据模型。

关于core-data - 在 CoreData 中保存 Swift CLLocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26790492/

相关文章:

swift - UIApplication.sharedApplication().delegate as! AppDelegate EXC_BREAKPOINT

objective-c - 自定义 NSURLProtocol 以显示/隐藏 NetworkActivityIndi​​cator

xcode - 如何初始化相互依赖的属性

快速获取位置然后加载表

ios - clocationmanager 在前几秒内返回零纬度和经度。我怎么能够

ios - Realm 过滤器 CLLocation

iphone - 如何对 NSPredicate 过滤的 coreData 属性求和?

ios - 核心数据: How to insert huge arrays to core data in swift?

ios - 单击以将图像添加到核心数据

ios - 代码 : Any way to refresh/re-run the playground?