2017-03-04 50 views
6

我正嘗試將json對象存儲到realm對象使用Objectmapper我收到來自Alamofire的響應後。下面是我寫的代碼:複合關鍵問題Realm Swift

func getTodayData() { 

    Alamofire.request("https://myapipoint.json").responseJSON{ (response) in 

     guard response.result.isSuccess, let value = response.result.value else { 
      return 
     } 
     let json = JSON(value) 


     guard let realm = try? Realm() else { 
      return 
     } 

     realm.beginWrite() 

     for (_, value): (String, JSON) in json { 

      let tpTodayOb = Mapper<TPToday>().map(JSONObject: value.dictionaryObject) 

      realm.add(tpTodayOb!, update: true) 
     } 

     do { 
      try realm.commitWrite() 
     } 
     catch { 
      print("Error") 
     } 
    } 
} 

我能夠從我的服務器映射json數據。但是,我的複合鍵存在問題。三個變量不是唯一的,但它們的組合是唯一的,所以我必須使用compoundKey作爲我的主鍵。我從compoundKey建設primaryKey如下:

public dynamic var compoundKey: String = "0-" 

public override static func primaryKey() -> String? { 
    // compoundKey = self.compoundKeyValue() 
    return "compoundKey" 
} 

private func compoundKeyValue() -> String { 

    return "\(yearNp)-\(mahina)-\(gate)" 
} 

這是我已經初始化我的三個變量。

func setCompoundID(yearNp: Int, mahina: String, gate: Int) { 
    self.yearNp = yearNp 
    self.mahina = mahina 
    self.gate = gate 
    compoundKey = compoundKeyValue() 
} 

compoundKeyGithub issues的定義在這裏。我有31個字典存儲在我的數據庫中,但我只能存儲最後一個字典。我確信這是一個複合關鍵問題,因爲此代碼庫能夠將數據存儲在具有唯一字段作爲主鍵的另一個表中,而在此數據庫表中則不是這種情況。我是否宣佈我的compoundKey錯誤?

回答

1

我沒有使用Alamofire,所以我假設你的代碼在Alamofire部分是正確的。你沒有給出你的JSON結構,基於上下文,我假設你的JSON包含31個字典。另外,我從一開始就假定Realm數據庫是空的。如果沒有,請將它清空。

我相信問題在這裏。

for (_, value): (String, JSON) in json { 
    let tpTodayOb = Mapper<TPToday>().map(JSONObject: value.dictionaryObject) 

    realm.add(tpTodayOb!, update: true) 
} 

請其更改爲

for (_, value): (String, JSON) in json { 
    let tpTodayOb = Mapper<TPToday>().map(JSONObject: value.dictionaryObject) 

    realm.add(tpTodayOb!, update: false) // you don't need `update:true`, unless you want to rewrite it intendedly 
} 

並運行項目。如果Realm引發重複的ID錯誤,則必須是初始化後您的compoundKey未成功更改。然後你應該檢查那部分。也許你應該手動調用它,或者覆蓋你的init函數的相應部分。

for (_, value): (String, JSON) in json { 
    let tpTodayOb = Mapper<TPToday>().map(JSONObject: value.dictionaryObject) 
    tpTodayOb.setCompoundID(yearNp: Int, mahina: String, gate: Int) 
    realm.add(tpTodayOb!, update: false) 
}