RealmSwift初始值设定项-Xcode修复-不断出错 [英] RealmSwift initializers - Xcode fix-it keeps getting it wrong

查看:107
本文介绍了RealmSwift初始值设定项-Xcode修复-不断出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想为一个类提供初始化程序时,我无法使Realm工作,Xcode不断提示错误.

I cannot get Realm working when I want to provide initializer for a class, Xcode endlessly suggest errors.

我决定上传两个屏幕截图而不是代码段,以便更轻松地查看错误

I decided to upload two screenshots instead of code snippet to make it easier to see errors

我遵循建议,并以此结束

I follow the suggestions and end up with this

最后一个错误告诉使用未声明的类型'RLMObjectSchema'

The last error tells "Use of undeclared type 'RLMObjectSchema'

我使用RealmSwift的最新0.99版本

I use the latest 0.99 version of RealmSwift

推荐答案

推荐的方法是创建成员级便利性初始化程序,如下所示:

The recommended way is creating memberwise convenience initializer, like the following:

class Item: Object {
    dynamic var isBook: Bool = true
    dynamic var numberOfPages: Double = 0
    dynamic var isInForeignLanguage: Bool = true
    dynamic var isFictional: Bool = true
    dynamic var value: Int {
        get {
            return calculalatedValue()
        }
    }

    convenience init(isBook: Bool, numberOfPages: Double, isInForeignLanguage: Bool, isFictional: Bool) {
        self.init()
        self.isBook = isBook
        self.numberOfPages = numberOfPages
        self.isInForeignLanguage = isInForeignLanguage
        self.isFictional = isFictional
    }

    ...
}

您不能省略默认初始化程序,因为Realm需要默认初始化程序来实例化查询对象.查询Realm时,Realm在内部调用默认的初始化程序以实例化对象.

You cannot omit default initializer because Realm needs default initializer for instantiating objects for querying. When querying to the Realm, Realm calls default initializer internally to instantiate the objects.

您也可以覆盖默认的初始值设定项,但我们不建议您这样做.因为当您覆盖默认的初始化程序时,由于Swift类型系统的限制,您应该覆盖从ObjC层继承的其他必需的初始化程序.另外,您应该同时导入RealmRealmSwift框架.因为这些初始值设定项的参数中只有Objective-C类.

You can also override default initializer, but we don't recommend it. Because when you override the default initializer, you should override other required initializers inherited from ObjC layer due to Swift type system limitation. Also you should import both Realm and RealmSwift frameworks. Because there are Objective-C only class in the parameters of those initializers.

import RealmSwift
import Realm // Need to add import if you override default initializer!

class Item: Object {
    dynamic var isBook: Bool = true
    dynamic var numberOfPages: Double = 0
    dynamic var isInForeignLanguage: Bool = true
    dynamic var isFictional: Bool = true
    dynamic var value: Int {
        get {
            return calculalatedValue()
        }
    }

    required init() {
        super.init()
    }

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

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

这篇关于RealmSwift初始值设定项-Xcode修复-不断出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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