Realm + Swift update object with JSON string
我正在使用alamofire从服务器获取响应JSON,然后使用ObjectMapper将字符串映射到Realm对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | The realm object is: class SolutionVideo: Object, Mappable { dynamic var svID = 0 dynamic var solutionTitle ="" dynamic var videoName ="" dynamic var relatedInfo ="" dynamic var shortDesc ="" override static func primaryKey() -> String? { return"svID" } required convenience init?(_ map: Map) { self.init() } func mapping(map: Map) { svID <- map["svID"] solutionTitle <- map["solutionTitle"] videoName <- map["videoName"] relatedInfo <- map["relatedInfo"] shortDesc <- map["shortDescription"] } |
} ??
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | The json string is: [ { "svID":"10", "solutionTitle":"Video10", "videoName":"Video10", "realtedInfo":"", "shortDescription":"" }, { "svID":"9", "solutionTitle":"Video9", "videoName":"Video9", "realtedInfo":"", "shortDescription":"" } ] in my viewController: @IBAction func updateBtn(sender: AnyObject) { // download file to update Realm let url ="http://janicedemo.com/updates.json" Alamofire.request(.GET, url).responseArray { (response: Response<[SolutionVideo], NSError>) in let Array = response.result.value print(Array) if let Array = Array { for video in Array { let dbURL = Realm.Configuration.defaultConfiguration.fileURL let realm = try! Realm(fileURL: dbURL!) try! realm.write{ print("will save") realm.add(video, update: true) } } } } |
问题是我可以成功添加对象。但是svID(prikey键)保留为0,而不是10或9(在JSON中设置)。是因为我已将默认值设置为svID吗?有人可以给我提示吗?谢谢
尝试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | class SolutionVideo: Object, Mappable { dynamic var svID = 0 dynamic var solutionTitle ="" dynamic var videoName ="" dynamic var relatedInfo ="" dynamic var shortDesc ="" func setCompoundID(id: Int) { self.svID = svID compoundKey = compoundKeyValue() } func setCompoundID(id: Int) { self.solutionTitle = solutionTitle compoundKey = compoundKeyValue() } func setCompoundID(id: Int) { self.videoName = videoName compoundKey = compoundKeyValue() } func setCompoundID(id: Int) { self.relatedInfo = relatedInfo compoundKey = compoundKeyValue() } func setCompoundID(id: Int) { self.shortDesc = shortDesc compoundKey = compoundKeyValue() } dynamic lazy var compoundKey: String = self.compoundKeyValue() override static func primaryKey() -> String? { return a€?compoundKeya€? } func compoundKeyValue() -> String { return"\\(svID)\\(solutionTitle)\\(videoName)\\(relatedInfo)\\(shortDesc)a€? } } |
我能想到的主要事情是主键值下降为字符串而不是适当的整数(即
根据ObjectMapper文档,您应该能够在映射函数中内联执行此转换:
1 | svID <- (map["svID"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } })) |
此外,作为一个旁注,我注意到您的JSON密钥名称之一存在拼写错误: