【问题标题】:Swift Realm Object and MappableSwift Realm 对象和可映射
【发布时间】:2017-06-26 23:09:09
【问题描述】:

我在swift中使用“Realm”和“ObjectMapper”

“Realm”不支持继承,所以我必须像这样制作模型:

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
}

我认为原因是函数“fetchLocal”只是返回“Object”而不是“Mappable”,但返回的类显然实现了“Mappable”,所以它通过了“if let as”子句,但调用时出现错误“toJSON()”。

由于“Realm Object”无法实现,我无法创建类似“ObjectMappable : Object, Mappable”的类并让“fetchLocal”函数返回“ObjectMappable”

所以,我认为唯一的选择是让“fetchLocal”函数返回一个实现“Object and Mappable”的类,但我不知道如何。

请帮帮我。

【问题讨论】:

标签: swift realm objectmapper


【解决方案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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2019-09-19
    相关资源
    最近更新 更多