【问题标题】:How can I get non-standard (transformable) attributes to update/save and persist using Core Data with Swift?如何使用带有 Swift 的 Core Data 获取非标准(可转换)属性来更新/保存和持久化?
【发布时间】:2016-04-21 04:18:52
【问题描述】:

我构建了一个非常基本的示例来演示我在尝试更新可转换类型并使更改在应用重新启动之间保持不变时遇到的问题。

我有一个 Destination...

类型的实体
import Foundation
import CoreData

class Destination: NSManagedObject {
    @NSManaged var name: String
    @NSManaged var location: 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")
    }
}

位置在 Core Data 中被配置为“可转换”,因为它具有其他基本类型都无法处理的结构。

使用 Apple 的样板 Core Data 代码,这是一个简单地执行以下操作的视图控制器:

  • 获取必要的 appDelegate / ManagedApplicationContext 引用
  • 如果存在则获取目的地,如果不存在则创建目的地
  • 打印目的地的名称和location.address
  • 更新目的地的名称和 location.address
  • 保存对 ManagedObjectContext 的更改

当应用程序运行并重新运行时,只有对名称的更改才会保留。对 location.address 所做的更改不会持续存在。

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

如何使目的地位置属性的更新持续存在?

【问题讨论】:

    标签: ios swift core-data


    【解决方案1】:

    Wain 的回答是正确的——似乎需要更改对对象的引用才能使 Core Data 持续更新。更改 Location 实例上的子属性不会更新该引用。变异和重新设置同一个对象也不起作用。只有分配了新的对象引用时,更改才会生效。

    以下是一些代码示例:

    工作:

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

    但这确实:

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

    如果 Location 类实现了 copyWithZone 方法,这也可以:

    let newLocation = destination.location.copy() as! Location
    newLocation.address = "another new street that sticks"
    destination.location = newLocation
    

    【讨论】:

      【解决方案2】:

      核心数据无法跟踪该对象的脏状态,因为它不了解其内部结构。与其改变对象,不如创建一个副本,改变它,然后设置新对象。它可能会改变然后重新设置相同的对象,不确定,没有测试过。

      你可以检查,只是改变地址,然后询问托管对象是否有变化,如果没有,则不会保存。

      【讨论】:

      • 谢谢,分配一个新对象效果很好。我测试了变异和重新设置同一个对象的情况,但这不起作用,可能是因为在这种情况下指针永远不会被更新。它真的想要一个全新的对象。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      相关资源
      最近更新 更多