按ID编辑所有记录(Swift 4,CoreData)

时间:2019-05-09 17:26:33

标签: swift core-data

我有 Int 个值

的数组

示例:

var SelectedCard = [Int]()

[3,1,2]


我需要按顺序

编辑所有记录

我尝试了此操作,但应用程序崩溃了

enter image description here

for item in 0...SelectedCard.count-1 {
        let order = SelectedCard[item]

        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        let managedContext = appDelegate.persistentContainer.viewContext

        let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Card")
        fetchRequest.predicate = NSPredicate(format: "order == %@", order)

        do {
            if let fetchResults = try managedContext.fetch(fetchRequest) as? [Card] {
                if fetchResults.count != 0 {
                    for index in 0...fetchResults.count-1 {
                        let managedObject = fetchResults[index]
                        managedObject.setValue("", forKey: "folderID")
                    }
                    appDelegate.saveContext()
                }
            }
        } catch {
            print(error)
        }
}
self.tableView.reloadData()

1 个答案:

答案 0 :(得分:2)

尝试将谓词更改为

NSPredicate(format: "order == \(order)")