簡體   English   中英

從核心數據 Swift 更新陣列(可轉換)中的單個 object

[英]Updating single object in array (Transformable) from core data Swift 4

我有一個名為“Contacts”的實體,其屬性名為“contactList”,類型為“Transformable”。 我試圖保存和刪除工作正常。 但更新特定記錄的值不起作用

這是我的代碼

   func updateRecord(primaryKey:String, mobileNumber:String) {
            if let appDelegate = UIApplication.shared.delegate as? AppDelegate{
                let context = appDelegate.persistentContainer.viewContext
                let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Contacts")

                do{
                    let objects = try context.fetch(fetchRequest)
                    if objects.count > 0{
                        for object in objects{
                            let match = object as! NSManagedObject
                            let list = match.value(forKey: "contactList") as? [String:Any]
                            if list != nil && !(list!.isEmpty) {
                                let key = list!["taskPrimaryKey"] as! String
                                if key == primaryKey{
                                  match.setValue(mobileNumber, forKeyPath: "Mobile")

                                    do {
                                        try context.save() // <- remember to put this :)
                                    } catch {
                                        // Do something... fatalerror
                                        print("fatalerror : \(error.localizedDescription)")
                                    }
                                    break
                                }
                            }
                        }

                    }
                } catch {
                    print("could not retrive error : \(error.localizedDescription)")
                }

            }
    }

我假設mobileNumber是一個number ??

match.setValue(NSNumber(mobileNumber), forKeyPath: "Mobile")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM