Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get non-standard (transformable) attributes to update/save and persist using Core Data with Swift?

I've constructed a very basic example to demonstrate the issue I'm having attempting to update a transformable type and get the change to persist between app restarts.

I have an entity of type Destination...

import Foundation
import CoreData

class Destination: NSManagedObject {
    @NSManaged var name: String
    @NSManaged var location: Location
}

... that has a simple name attribute (of type String) and an attribute of type Location:

import Foundation

class Location: NSObject, NSCoding {
    var address: String
    var latitude: Double
    var longitude: Double

    required init?(coder aDecoder: NSCoder) {
        address = aDecoder.decodeObjectForKey("Address") as? String ?? ""
        latitude = aDecoder.decodeObjectForKey("Latitude") as? Double ?? 0.0
        longitude = aDecoder.decodeObjectForKey("Longitude") as? Double ?? 0.0
        super.init()
    }

    init(address: String, latitude: Double, longitude: Double) {
        self.address = address
        self.latitude = latitude
        self.longitude = longitude

        super.init()
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(address, forKey: "Address")
        aCoder.encodeObject(latitude, forKey: "Latitude")
        aCoder.encodeObject(longitude, forKey: "Longitude")
    }
}

Location is configured as "transformable" in Core Data, because it has structure that none of the other basic types can handle.

Using Apple's boilerplate Core Data code, here's a view controller that simply does the following:

  • Gets the necessary appDelegate / ManagedApplicationContext references
  • Fetches a destination if one exists, creates one if not
  • Prints the name and location.address of the destination
  • Updates the name and location.address of the destination
  • Saves changes to the ManagedObjectContext

When the app is run and re-run, only changes to the name will persist. Changes made to the location.address do not persist.

import UIKit
import CoreData

class ViewController: UIViewController {

    var appDelegate: AppDelegate!
    var context: NSManagedObjectContext!

    override func viewDidLoad() {
        super.viewDidLoad()
        updateDestination()
    }

    func updateDestination() {
        var destination: Destination
        appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        context = appDelegate.managedObjectContext

        if let dest = fetchOneDestination() {
            destination = dest
        }
        else {
            destination = create()!
        }
        print("destination named: \(destination.name), at: \(destination.location.address)")

        destination.name = "New name of place that will update and persist"
        destination.location.address = "123 main st (change that will never persist)"
        appDelegate.saveContext()
    }

    func create() -> Destination? {
        guard let newDestination = NSEntityDescription.insertNewObjectForEntityForName("Destination", inManagedObjectContext: context) as? Destination else {
            return nil
        }
        newDestination.name = "Original name of place that can be updated"
        newDestination.location = Location(address: "100 main st", latitude: 34.051145, longitude: -118.243595)
        return newDestination
    }

    func fetchOneDestination() -> Destination? {
        let request = NSFetchRequest()
        request.entity = NSEntityDescription.entityForName("Destination", inManagedObjectContext: context)
        do {
            let fetchResults = try context.executeFetchRequest(request)
            if fetchResults.count > 0 {
                if let dest = fetchResults[0] as? Destination {
                    return dest
                }
            }
        }
        catch {}
        return nil
    }
}

How can I make updates to the destination's location attribute persist?

like image 271
Dan G Avatar asked Apr 21 '16 04:04

Dan G


1 Answers

Wain's answer is correct- it seems that the reference to the object needs to change in order for Core Data to persist the update. Changing a child attribute on the Location instance will not update that reference. Nor will it work to mutate and re-set the same object. Only when a new object reference is assigned will the change stick.

Here are some code examples:

This does NOT work:

let newLocation = destination.location
newLocation.address = "a new street that doesn't stick"
destination.location = newLocation

But this does:

destination.location = Location(address: "a new street that sticks", latitude: 34.051145, longitude: -118.243595)

This also works, providing that the Location class implements the copyWithZone method:

let newLocation = destination.location.copy() as! Location
newLocation.address = "another new street that sticks"
destination.location = newLocation
like image 135
Dan G Avatar answered Sep 25 '22 00:09

Dan G