Search code examples
iosswiftrealm

Can't access properties in Realm Object subclass


I have a realm object subclass that gets instantiated each time a location is tapped on a map. My Realm Object subclass is:

final class MapLocation:Object {
    @objc var text = ""
    @objc var latitude = Double()
    @objc var longitude = Double()
}

In my map view controller (a GMSMapViewDelegate), I am adding the locations on each tap of the map:

func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
    let lat = coordinate.latitude
    let lon = coordinate.longitude
    index += 1

    let marker = GMSMarker()
    marker.position = coordinate
    marker.map = mapView

    try! realm?.write {
        let location = MapLocation(value: ["latitude":lat, "longitude":lon, "text":"locaton-\(index)"])
        self.items.append(location)
        self.items.realm?.add(location)
    }
}

When this view controller loads, I want to display any points that were created in a previous session. I am doing this as follows:

private func initMap(withPoints list:List<MapLocation>){
    for location in list {
        let newMarker = GMSMarker()
        let lat = location.latitude
        let lon = location.longitude
        newMarker.title = location.text
        newMarker.position = CLLocationCoordinate2D(latitude: lat, longitude: lon)
        newMarker.map = mapView
    }
}

In this for loop, I have verified that I am retrieving the persisted list of MapLocation objects. When I do po print(location)while inside this loop, I correctly get the following:

MapLocation {
    text = locaton-1;
    latitude = 50.73600783337027;
    longitude = 4.882587678730488;
}

Here is my problem. I am unable to access any of these properties. For instance:

(lldb) po print(location)
MapLocation {
    text = locaton-1;
    latitude = 50.73600783337027;
    longitude = 4.882587678730488;
}
(lldb) po print(location.longitude)
0.0
(lldb) po print(location.latitude)
0.0
(lldb) po print(location.text)
nil
(lldb) 

As is shown here, the properties are stored, but when retrieving them they are unavailable. Can anyone tell me why this is happening? Thanks!


Solution

  • You need to mark your properties as dynamic.