我正在使用 ObjectMapper 将 JSON 对象解析为领域。
我的班级旅行看起来像这样:
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"];
}
}
我正在使用 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
}
在上面的代码中,当我打印测试时,我得到:
(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"
}
当我打印时,firstTrip,我得到
(AwesomeApp.Trip?) firstTrip = 0x0000000154f1f370 {
RealmSwift.Object = {
Realm.RLMObjectBase = {
ObjectiveC.NSObject = {}
}
}
Id = nil
CreatedOn = nil
LastModified = nil
}
我使用了领域浏览器,看起来值已正确写入数据库。但是,读取这些值会返回一个包含所有 nil 值的行程对象。为什么是这样 ?
编辑:我打印了 allTripsprint (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;
}
)