Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm Swift returning objects with all nil values

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;
    }
 )
like image 379
Ashish Agarwal Avatar asked Feb 17 '16 08:02

Ashish Agarwal


1 Answers

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.

like image 163
bdash Avatar answered Nov 05 '22 19:11

bdash