Realm object returns nil (Swift)

I have my own polygon object, so I can save map overlays in Realm. I can successfully create these objects, but when I want to get the var polygon object, it returns nil. When I print a polygon object, it prints it perfectly, with all the data.

This is an example of what it prints.

CustomPolygon { name = Polygon1; id = p1; polygon = Polygon { coordinates = RLMArray <0x7f928ef36230> ( [0] Coordinate { latitude = -36.914167; longitude = 174.904722; }, [1] Coordinate { latitude = -36.9325; longitude = 174.957222; }, . . . ); }; } 

My function to load data from Realm

 func loadOverlaysFromRealm(){ do { let realm = try Realm() let polygons = realm.objects(CustomPolygon) for p in polygons { var coordinates = [CLLocationCoordinate2D]() print(p) // !!!!! prints out what is above print(p.polygon) // !!!!! Returns nil. if let coordinateList = p.polygon?.coordinates as? List<Coordinate> { for coordinate in coordinateList { coordinates.append(CLLocationCoordinate2DMake(coordinate.latitude, coordinate.longitude)) } } print(coordinates) // prints "[]" let polygon = MKPolygon(coordinates: &coordinates, count: coordinates.count) self.map.addOverlay(polygon) } } catch let error as NSError { print(error.localizedDescription) } } 

My classes

 class CustomPolygon: Object { var name:String = "" var id:String = "" var polygon:Polygon? = nil } class Polygon: Object { var coordinates = List<Coordinate>() } class Coordinate: Object { var latitude:Double = 0.0 var longitude:Double = 0.0 } 
+5
source share
1 answer

The String , Double and Object properties of your Object subclasses must be declared using the dynamic modifier to allow Realm to override the getter and setter properties. Without this, the Swift compiler will directly access the instance variable of the object, which prevents Realm from reading or writing data from the Realm file. See the Realm cheatsheet model property for a quick overview of how to declare the properties of each of the supported types.

+9
source

All Articles