如何在IOS CoreData中使用Swift将MKPolyline属性存储为可转换的形式?

9
需要在Swift中允许将MKPolyline存储在CoreData中的代码是什么?
例如,如果我有一个Core Data实体(称为“myEntity”),我想保存一个MKPolyline,并将“polyline”字段添加为可转换项,并在xcode中将其设置为“transformable”。 还需要生成NSManagedObject子类。
myEntity.swift
import UIKit
import CoreData
import MapKit
class myEntity: NSManagedObject {
}

myEntity+CoreDataProperties.swift

import Foundation
import CoreData
extension myEntity {
    @NSManaged var title: String
    @NSManaged var polyline: NSObject? 
}

问题 - 什么代码是必须的才能使这个工作?

(我注意到这篇帖子是关于objective-c的,但我很难理解/移植/让它工作 - 如何在Core Data中存储NSMutable数组的数据?)

1个回答

8

将折线对象归档并保存到Core Data中:

    let context = self.fetchedResultsController.managedObjectContext
    let entity = self.fetchedResultsController.fetchRequest.entity!
    let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context)
    let polylineObj = polyline() // For test purpose.
    let polylineData = polylineToArchive(polylineObj)
            newManagedObject.setValue(polylineData, forKey: "polyline")
        context.save()

NSManagedObject中解档折线:

    let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
    let data = object.valueForKey("polyline") as! NSData
    let polyline = polylineUnarchive(data)
    log(polyline!)

MKPolyline的存档和解档函数,以及一些辅助函数。

func polylineUnarchive(polylineArchive: NSData) -> MKPolyline? {
    guard let data = NSKeyedUnarchiver.unarchiveObjectWithData(polylineArchive),
        let polyline = data as? [Dictionary<String, AnyObject>] else {
        return nil
    }
    var locations: [CLLocation] = []
    for item in polyline {
        if let latitude = item["latitude"]?.doubleValue,
            let longitude = item["longitude"]?.doubleValue {
            let location = CLLocation(latitude: latitude, longitude: longitude)
            locations.append(location)
        }
    }
    var coordinates = locations.map({(location: CLLocation) -> CLLocationCoordinate2D in return location.coordinate})
    let result = MKPolyline(coordinates: &coordinates, count: locations.count)
    return result
}

func polylineToArchive(polyline: MKPolyline) -> NSData {
    let coordsPointer = UnsafeMutablePointer<CLLocationCoordinate2D>.alloc(polyline.pointCount)
    polyline.getCoordinates(coordsPointer, range: NSMakeRange(0, polyline.pointCount))
    var coords: [Dictionary<String, AnyObject>] = []
    for i in 0..<polyline.pointCount {
        let latitude = NSNumber(double: coordsPointer[i].latitude)
        let longitude = NSNumber(double: coordsPointer[i].longitude)
        let coord = ["latitude" : latitude, "longitude" : longitude]
        coords.append(coord)
    }
    let polylineData = NSKeyedArchiver.archivedDataWithRootObject(coords)
    return polylineData
}

func polyline() -> MKPolyline {
    let locations = [CLLocation(latitude: 37.582691, longitude: 127.011186), CLLocation(latitude: 37.586112,longitude: 127.011047), CLLocation(latitude: 37.588212, longitude: 127.010438)]
    var coordinates = locations.map({(location: CLLocation) -> CLLocationCoordinate2D in return location.coordinate})
    let polyline = MKPolyline(coordinates: &coordinates, count: locations.count)
    return polyline
}

func log(polyline: MKPolyline) {
    let coordsPointer = UnsafeMutablePointer<CLLocationCoordinate2D>.alloc(polyline.pointCount)
    polyline.getCoordinates(coordsPointer, range: NSMakeRange(0, polyline.pointCount))
    var coords: [Dictionary<String, AnyObject>] = []
    for i in 0..<polyline.pointCount {
        let latitude = NSNumber(double: coordsPointer[i].latitude)
        let longitude = NSNumber(double: coordsPointer[i].longitude)
        let coord = ["latitude" : latitude, "longitude" : longitude]
        coords.append(coord)
    }
    print(coords)
}

哇,非常感谢。让我尽快测试,然后接受。顺便问一下,这种方法在IOS更新之间是否应该被出售? - Greg
@Greg 是的。这个功能在iOS更新之间非常稳定。我的例子只是存档和取消存档坐标。如果你想要从MKPolyline存档更多的东西,那么就需要添加额外的代码。 - Ramis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接