使用Realm存储数据,添加对象清除列表上的对象

时间:2016-04-25 13:02:37

标签: ios swift realm

我刚开始使用Realm也使用ObjectMapper保存数据。我遇到的问题是:

ObjectInList通常具有id = 0和symbol =“CA”,映射后它具有不同的数据,如id = 0,symbol =“First Name,Last name”。

let database开始之前,我已将数据存储在profileDictionary变量中,并且在database.add(profileDictionary) 之后,对象列表的内容已更改为初始数据,如

id = 0

symbol = "CA"

有意思的是,变量testInt没有改变它的值,等于10。

感谢您的建议!

class ObjectInList: Object, Mappable{
    dynamic var id : Int = 0
    dynamic var symbol : String = "CA"

    convenience required init?(_ map: Map) {
       self.init()
    }

    func mapping(map: Map) {
        id <- map["id"]
        symbol <- map["symbol"]
    }
}

class ProfileDictionaries: Object, Mappable{
    dynamic var testInt : Int = 20
    var states = List<ObjectInList>()

    convenience required init?(_ map: Map) {
        self.init()
    }

    func mapping(map: Map) {
    // ObjectMapper does not support List<Object>() collections.
        testInt = 10
        var array: [ObjectInList] = []
        array <- map["states"]
        states.appendContentsOf(array)
    }
}

SwiftEventBus.onMainThread(self, name: Constants.ServerResponse.PROFILE_DICTIONARIES_SUCCESS){
  result in

  let profileDictionary  = result.object as? ProfileDictionaries ?? ProfileDictionaries()
   self.removeDatabase()

   do{
       let database = try Realm()
       try! database.write {
       database.add(profileDictionary)
       let localProfileDictionaries = database.objects(ProfileDictionaries)
   }
   catch let error as NSError{
       print(error)
       self.removeDatabase()
   }
}

1 个答案:

答案 0 :(得分:0)

这篇文章帮助了我 - Swift Realm: After writing transaction reference set to nil

我们应该在LLDB调试器中使用PO而不是P - 数据存储正确!