2017-08-04 55 views
0

我有一個核心數據條目,其中某些鍵和值存儲在從API中提取的數據庫中。現在我想更新與更新值的一些核心數據條目,爲此我使用如下代碼:核心數據條目在swift3中未正確更新

func updateAllRecords(responseArray: [Dictionary<String, String>]) { 
    for settingsObject in responseArray { 
    if #available(iOS 10.0, *) { 
     let keys = settingsObject.flatMap() { $0.0 as? String } 
     let values = settingsObject.flatMap(){ $0.1 as? String} 
     let request = NSFetchRequest<ApplicationSettings>(entityName: "ApplicationSettings") 

     do { 
     let context = persistentContainer.viewContext 
     let searchResults = try context.fetch(request) 

     for settingsKeys in searchResults { 

     if keys.contains(settingsKeys.key!) { 
      settingsKeys.value = values[1] 
      try context.save() 
      } 
     } 

     } catch { 
     print ("There was an error") 
     } 

    } else { 

     } 
    } 
    } 
} 

我打電話從視圖 - 控制這個功能是這樣的:

var dicArray = [Dictionary<String, String>]() 
        let dic1 = ["IS_CIVIL_ID_MANDATORY": "Smith", "TIME_IN_MIN_BEFORE_ENABLING_START_TRIP": "Robert"] 
        dicArray.append(dic1) 
        CoreDataHandler.sharedInstance.updateAllRecords(responseArray: dicArray) 

但表中的條目未正確更新密鑰。它爲兩個鍵存儲相同的值。請看下圖:

Data base

如果我錯了,在這段代碼?爲什麼相同的值存儲在鍵上?

+0

settingsKeys.value =值[1]它是靜態的替代值[1]與您的價值 –

+0

你好@Chelsea任何疑問在我的答案? –

回答

1

你犯的錯誤這裏
settingsKeys.value = values[1]這裏1是靜態

我覺得你不需要值陣列分離 只是我的代碼

for settingsKeys in searchResults { 

     if keys.contains(settingsKeys.key!) 
     { 
      settingsKeys.updateValue(settingObject[settingsKeys.key!], forKey:settingsKeys.key!) 
      try context.save() 
      } 
     } 

     } 

對於演示示例

替換此代碼
func updateAllRecords(responseArray: [Dictionary<String, String>]) 
{ 
    for settingsObject in responseArray 
    { 

      var dic2 = ["IS_CIVIL_ID_MANDATORY": "xyz", "TIME_IN_MIN_BEFORE_ENABLING_START_TRIP": "xyz"] 
      let keys = settingsObject.flatMap() {$0.0} 
      let values = settingsObject.flatMap(){$0.1} 
      let settingKeys = dic2.flatMap() {$0.0} 

      for settingsKey in settingKeys 
      { 

       dic2.updateValue(settingsObject[settingsKey]!, forKey: settingsKey) 

      } 
      print(keys) 
     print(dic2) 
    } 
} 
var dicArray = [Dictionary<String, String>]() 
let dic1 = ["IS_CIVIL_ID_MANDATORY": "Smith", "TIME_IN_MIN_BEFORE_ENABLING_START_TRIP": "Robert"] 
dicArray.append(dic1) 
updateAllRecords(responseArray: dicArray) 

輸出

[ 「TIME_IN_MIN_BEFORE_ENABLING_START_TRIP」: 「羅伯特」, 「IS_CIVIL_ID_MANDATORY」: 「史密斯」]

+0

updateValue它是Dictionary的屬性嗎? –

+0

是的,它是字典的屬性 –

+0

@ChelseaShawra我已經創建了它的演示檢查「xyz」被替換爲相應的值 –