领域对象返回nil(Swift) [英] Realm Object returning nil (Swift)

查看:126
本文介绍了领域对象返回nil(Swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义多边形对象,因此可以将地图叠加层保存到Realm.我能够成功创建此对象,但是当我想要检索var多边形对象时,它将返回nil.当我打印多边形对象时,它会很好地打印所有数据.

I have a custom polygon object so I can save map overlays to Realm. I'm able to create this objects successfully, but when I want to retrieve the var polygon object it returns nil. When I print the polygon object, it prints it out fine, with all the data.

这是打印输出的示例.

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;
            }, . . . 
        );
    };
}

我从Realm加载数据的功能

My Function for loading 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)
    }
}

我的课程

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
}

推荐答案

Object子类的StringDoubleObject属性需要使用dynamic修饰符声明,以使Realm能够覆盖属性的getter和setter.否则,Swift编译器将直接访问对象的实例变量,这不会为Realm提供任何从Realm文件读取或写入数据的机会.请参阅Realm的模型属性速查表,以快速了解如何声明每个支持的类型.

The String, Double and Object properties of your Object subclasses need to be declared with the dynamic modifier to allow Realm to override the getter and setter of the property. Without this the Swift compiler will access the object's instance variable directly, which doesn't provide any opportunity for Realm to read or write data from the Realm file. See Realm's model property cheatsheet for a quick overview of how to declare properties of each of the supported types.

这篇关于领域对象返回nil(Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆