【发布时间】: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
}
}
如何使目的地位置属性的更新持续存在?
【问题讨论】: