重新启动应用程序时,为什么我的CoreData更新没有持久化?

时间:2019-03-02 05:12:28

标签: ios swift

我正在尝试编辑CoreData中先前保存的对象中的值。

该对象似乎已更新,直到我重新启动了该应用程序,并且该值现在设置为“ nil”。

这是我保存更改的方法:

class SaveNewQuickShareTrip: NSManagedObject {

    static func addNewTrip(_ username: String, newTrip: TripModel, tripType : String, in context: NSManagedObjectContext) {

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: Constants.User)
        request.predicate = NSPredicate(format: "username=%@", username)
        request.returnsObjectsAsFaults = false

        var currentTrips : [TripModel] = Array<TripModel>()

        do {
            let matches = try context.fetch(request)

            if matches.count == 1 {
                for userData in matches as! [NSManagedObject] {
                    currentTrips = userData.value(forKey: tripType) as! Array<TripModel>
                    print("currentTrips OLD count = ", currentTrips.count)
                    currentTrips.append(newTrip)
                    userData.setValue(currentTrips, forKey: Constants.quickShareTrips)
                    print("currentTrips NEW count = ", currentTrips.count)
                }
                do {
                    try context.save()
                } catch {
                    print("Saving the new trip failed!")
                }
            }
        } catch {
            print("Something went wrong when saving the quick share trip.")
        }
    }
}

我用来在启动时检索对象的代码:

class UserRetrieval: NSManagedObject {

    static func fetchUser(_ username: String, in context: NSManagedObjectContext) -> [NSManagedObject] {

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: Constants.User)
        request.predicate = NSPredicate(format: "username=%@", username)
        request.returnsObjectsAsFaults = false

        var theUser = [NSManagedObject]()

        do {
            let matches = try context.fetch(request)

            if let records = matches as? [NSManagedObject] {
                theUser = records
            }
        } catch {
            print("Can't find User.")
        }

        return theUser
    }
}

0 个答案:

没有答案