如何在 IOS 核心数据中使用 swift 将 MKPolyline 属性存储为可转换? [英] How to store an MKPolyline attribute as transformable in IOS coredata with swift?

查看:30
本文介绍了如何在 IOS 核心数据中使用 swift 将 MKPolyline 属性存储为可转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

允许快速在 CoreData 中存储 MKPolyline 所需的代码是什么.

What would be the code required to allow the storage of an MKPolyline in CoreData in swift.

例如,如果我有一个核心数据实体(比如myEntity"),我想为其保存 MKPolyline,并将polyline"字段添加为可转换,并将其设置为transformable"代码.也产生了 NSManagedObject 子类.

So for example if I had one of my core data entities (say "myEntity") for which I wanted to save an MKPolyline, and have added the "polyline" field as transformable, and have set it to "transformable" in xcode. Also have produced NSManagedObject subclass.

myEntity.swift

myEntity.swift

import UIKit
import CoreData
import MapKit
class myEntity: NSManagedObject {
}

myEntity+CoreDataProperties.swift

myEntity+CoreDataProperties.swift

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

问题 - 需要什么代码才能使其工作?

Question - What code is required to allow this to work?

(我确实注意到这篇文章是目标 c,但是我正在努力理解/移植/让它工作 - 你如何将 NSMutable Array 中的数据存储在 Core Data 中? )

( I do note this post re objective-c, however I'm struggling to understand/port/get this to work - How do you store data from NSMutable Array in Core Data? )

推荐答案

归档折线对象并保存到核心数据:

Archive polyline object and save to 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 归档和解归档功能.还有一些辅助函数.

MKPolyline arhiver and unarchiver functions. As well some helper functions.

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 核心数据中使用 swift 将 MKPolyline 属性存储为可转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆