I am using ObjectMapper to parse JSON objects into 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.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
(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. However, reading the values returns a trip object with all nil values. Why is this ?
EDIT: I printed allTrips using print (allTrips)
and this printed out:
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. 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. This is why the instance variables do not have the values you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With