简体   繁体   English

无法将具有通用类型的类添加到快速领域

[英]Can not add class with generic type to swift realm

I need to save a class in realm, this class contains a generic type as the following:- 我需要在领域中保存一个类,该类包含以下通用类型:-

@objcMembers
class ClassA<T: Object & Codable>: Object, Codable {
    dynamic var key: String?
    dynamic var type: T?

    override class func primaryKey() -> String {
        return "key"
    }

}

@objcMembers
class ClassB: Object, Codable {    
}

let object: ClassA<ClassB> 

realm.add(object, update: true)

But this code unfortunately save only ClassA.key in realm and ignors ClassA.type. 但是不幸的是,此代码仅将ClassA.key保存在领域中并忽略了ClassA.type。

I have googled about this issue but without any result unfortunately. 我已经用谷歌搜索了这个问题,但不幸的是没有任何结果。 It seems that nobody uses a generic type inside a realm class. 似乎没有人在领域类中使用泛型类型。

Finally I've reached the proper solution. 终于我找到了正确的解决方案。 I have used the advantage of the generic realm list type, then I have modified the “type” variable to be a list of generic instead of single generic object. 我利用了通用领域列表类型的优势,然后将“ type”变量修改为通用列表而不是单个通用对象的列表。 It is now working fine with me. 现在,我可以正常使用。 Now I can easily use a generic type inside a class and save this class to realm without any problem. 现在,我可以轻松地在类中使用泛型类型并将该类保存到领域,而不会出现任何问题。

@objcMembers
class ClassA<T: Object & Codable>: Object, Codable {
    dynamic var key: String?
    var type: List<T>()

    override class func primaryKey() -> String {
        return "key"
    }

}

@objcMembers
class ClassB: Object, Codable {    
}

let object: ClassA<ClassB>

realm.add(object, update: true)

@objcMembers only exposes compatible members to Objective-C. @objcMembers仅将兼容成员公开给Objective-C。 Swift generics do not get included with this as they are not compatible with Objective-C. Swift泛型不包含在其中,因为它们与Objective-C不兼容。 Realm works off of exposing the members to Objective-C. Realm的工作原理是将成员暴露于Objective-C。

Possible solution: 可能的解决方案:

@objcMembers
class ClassA<T: Object & Codable>: Object, Codable {
    dynamic var key: String?
    var type: T?

    override class func primaryKey() -> String {
        return "key"
    }

}

@objcMembers
class ClassB: Object, Codable {

}

class ClassABComposite: ClassA<ClassB> {
    // T can be realized as ClassB here
    override var type: ClassB? {
        set {
            backingType = newValue
        }
        get {
            return backingType
        }
    }

    // This will work because it's not generic
    @objc dynamic var backingType: ClassB?
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM