Swift Realm对象和Mappable

时间:2017-02-09 04:28:12

标签: swift realm objectmapper

我正在使用" Realm"和#34; ObjectMapper"在快速

"境界"不支持继承,所以我必须制作这样的模型:

class Model1 : Object, Mappable
class Model2 : Object, Mappable

我想创建一个函数,用字符串和主键查找模型名称的本地数据。

func fetchLocal(name : String, key : String)->Object{
    switch(name){
        case "Model1":
            ~~~~
            return Model1
        case "Model2":
            ~~~~
            return Model2
    }
}

当我使用此功能时,将对象强制转换为Mappable

if let mappable = fetchLocal(name : "Model1", key: "~~~~") as? Mappable{
    let json = mappable.toJSON()
}

然后出现运行时错误,没有如下信息:

Thread 1: EXC_BAD_ACCESS (code = 1, address = 0x0)

我跟踪了这​​个错误,但应用程序只是在Mappable.swift崩溃:

public func toJSON() -> [String: Any] {
    return Mapper().toJSON(self)         <------here
}

我认为原因是函数&#34; fetchLocal&#34;只需返回&#34;对象&#34;不是&#34; Mappable&#34;,但返回课程显然是实现&#34; Mappable&#34;,所以它通过&#34;如果让#as;&#34;子句,但在调用&#34; toJSON()&#34;。

时出现错误

As&#34; Realm Object&#34;无法实现,我不能创建像#34; ObjectMappable这样的类:Object,Mappable&#34;并让&#34; fetchLocal&#34;函数返回&#34; ObjectMappable&#34;

所以,我认为唯一的选择就是制作&#34; fetchLocal&#34;函数返回一个实现&#34; Object和Mappable&#34;的类,但我不知道如何。

请帮助我。

1 个答案:

答案 0 :(得分:1)

public class Model: Object, Mappable {

    public required init(map: Map) {
        super.init()
    }

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

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

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

    public override init(value: Any) {
        super.init(value: value)
    }

    public func mapping(map: Map) {

    }

}

领域查询

func fetchLocal<AnyModel: Model>( type: AnyModel.Type, key: String ) -> AnyModel {
    yourRealm.object(ofType: type, forPrimaryKey: key)
}

任何型号

class Model1 : Model {

}

选择

let m:Model1? = fetchLocal(type: Model1.self, key: "1")