Realm.objects(Type)返回空对象

时间:2016-07-18 01:37:51

标签: swift realm

我是Xcode开发的新手,我需要一些Realm数据库的帮助 ..这些是我的桌子

class Parent: Object {
    var id :Int = 0
    var name: String = ""
}

class Surah: Parent {
    dynamic var ayatNum = 0

    private var fav : Bool {
        set { self.fav = newValue }
        get { return self.fav }
    }

    init(id: Int , ayat: Int , name: String) {
        super.init()
        super.id = id
        self.ayatNum = ayat
        super.name = name
    }

    override static func primaryKey() -> String? {
        return "id"
    }

    required init(realm: RLMRealm, schema: RLMObjectSchema) {
        super.init()
    }

    required init(value: AnyObject, schema: RLMSchema) {
        super.init()
    }

    required init() {
        super.init()
    }
}

class Reader: Parent{
    private var fav: Bool {
        set { self.fav = newValue }
        get { return self.fav }
    }

    init(id: Int , name: String) {
        super.init()
        self.id = id
        self.name = name

    }

    override static func primaryKey() -> String? {
        return "id"
    }

    required init(realm: RLMRealm, schema: RLMObjectSchema) {
        super.init()
    }

    required init(value: AnyObject, schema: RLMSchema) {
        super.init()
    }

    required init() {
        super.init()
    }
}

当我调用这些行并将结果存储在一个数组中并打印出来时

realm = try!Realm()
readers = Array(realm.objects(Reader.self))
print(readers)

我也试试这个

readers = Array(try!Realm().objects(Reader.self))
print(readers)

它打印一个空对象

Reader {
    id = 0;
    name = ;
}, Reader {
    id = 0;
    name = ;
}, Reader {
    id = 0;
    name = ;
}

我在stackoverflow中搜索这个问题并找到那个没有解决我问题的解决方案

Realm.objects() returns empty objects

任何人都可以帮助我!!

2 个答案:

答案 0 :(得分:3)

因为您的Parent类属性未声明为dynamic。 Realm中的大多数属性必须声明为dynamic(Exception是List和LinkingObjects)。 Realm为了性能而懒洋洋地加载了所有值。所有属性访问都在运行时替换为专用访问器。因此,您应该将属性声明为dynamic。如下所示:

class Parent :Object{
    dynamic var id: Int=0
    dynamic var name: String=""
}

请参阅https://realm.io/docs/swift/latest/#cheatsheet

此外,使用Surah初始化程序,Reader类和convenience类将更加简单。如果是这样,您就不需要覆盖init(realm: RLMRealm, schema: RLMObjectSchema)init(value: AnyObject, schema: RLMSchema)init()

class Surah :Parent {
    dynamic var ayatNum = 0

    private var fav : Bool {
        set { self.fav = newValue }
        get { return self.fav }
    }

    convenience init(id: Int , ayat:Int , name:String) {
        self.init()
        self.id = id
        self.ayatNum = ayat
        self.name = name

    }
}

class Reader : Parent {
    private var fav : Bool {
        set { self.fav = newValue }
        get { return self.fav }
    }

    convenience init(id: Int , name:String) {
        self.init()
        self.id = id
        self.name = name
    }

    override static func primaryKey() -> String? {
        return "id"
    }

}

答案 1 :(得分:-1)

尝试从领域添加get对象

Math.abs(Y % 360))