简体   繁体   English

Realm Swift返回所有nil值的对象

[英]Realm Swift returning objects with all nil values

I am using ObjectMapper to parse JSON objects into Realm. 我使用ObjectMapper将JSON对象解析为Realm。

My class Trip looks like this: 我的班级旅行看起来像这样:

class Trip: Object, Mappable {
    dynamic var Id : String? = nil
    dynamic var CreatedOn : String? = nil
    dynamic var LastModified : String? = nil

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

    func mapping(map: Map) {
        Id <- map["Id"];
        CreatedOn <- map["CreatedOn"];
        LastModified <- map["LastModified"];
    }
}

I am calling a web service request using Alamofire: 我正在使用Alamofire调用Web服务请求:

Alamofire.request(.GET, path, headers: ["Token" : auth_token]).responseJSON { response in

    let dict : NSDictionary? = response.result.value as? NSDictionary

    let test = Mapper<Trip>().map(dict!)
    let realm = try! Realm()
    realm.beginWrite()
    realm.add(test!)
    try! realm.commitWrite()

    let alltrips : Results<Trip> = realm.objects(Trip)
    let firstTrip = alltrips.first
}

In the above code, when I print test, I get: 在上面的代码中,当我打印测试时,我得到:

(AwesomeApp.Trip?) test = 0x0000000154e8f0d0 {
  RealmSwift.Object = {
    Realm.RLMObjectBase = {
      ObjectiveC.NSObject = {}
    }
  }
  Id = "47d86d34-b6f2-4a9f-9e31-30c81a915492"
  CreatedOn = "2016-01-20T23:39:41.995Z"
  LastModified = "2016-01-20T23:44:39.363Z"
}

When I print, firstTrip, I get 当我打印,firstTrip,我明白了

(AwesomeApp.Trip?) firstTrip = 0x0000000154f1f370 {
  RealmSwift.Object = {
    Realm.RLMObjectBase = {
      ObjectiveC.NSObject = {}
    }
  }
  Id = nil
  CreatedOn = nil
  LastModified = nil
}

I used the Realm Browser and it looks like the values have been written to the database correctly. 我使用了Realm Browser,看起来这些值已正确写入数据库。 However, reading the values returns a trip object with all nil values. 但是,读取值将返回具有所有nil值的trip对象。 Why is this ? 为什么是这样 ?

EDIT : I printed allTrips using print (allTrips) and this printed out: 编辑 :我使用print (allTrips)并打印出来:

Results<Trip> (
    [0] Trip {
        Id = 47d86d34-b6f2-4a9f-9e31-30c81a915492;
        CreatedOn = 2016-01-20T23:39:41.995Z;
        LastModified = 2016-01-20T23:44:39.363Z;
    }
 )

The instance variables of a Realm Object subclass are only used for objects that have not yet been added to a Realm. Realm Object子类的实例变量仅用于尚未添加到Realm的对象。 After an object has been added to a Realm, or for an object that was retrieved from a Realm, the objects getters and setters access data directly from the Realm without the use of the instance variables. 将对象添加到Realm或从Realm检索到的对象后,对象getter和setter直接从Realm访问数据,而不使用实例变量。 This is why the instance variables do not have the values you expect. 这就是实例变量没有您期望的值的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM