Saving Swift CLLocation in CoreData

You will have much less trouble when you create a NSManagedObject subclass for the CLLocation objects. Then create methods for storing and retrieving for convenience:

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
        )
    }

You have to set up your data model with an entity according to this class.


What you are missing is that NSValue is for storing types, i.e., contiguous blocks of memory, not objects. CLLocation is an object.

In order to store a CLLocation in core data, you will have to store each of the properties. An alternative is to use a Coder.