Swift+Realm1.0.1+Alamofire(一)

Q:使用realm繼承的object不能實現(xiàn)歸檔解檔?

required init?(coder aDecoder: NSCoder) {
        self.init()
        self.name = aDecoder.decodeObjectForKey("name") as! String
        self.updated = aDecoder.decodeObjectForKey("updated") as! NSDate
    }

當(dāng)實現(xiàn)上面的方法的時候xcode會強制性的向你提出還需要實現(xiàn)其他幾個init方法,對,這沒錯,但是當(dāng)你實現(xiàn)了

    required init(realm: RLMRealm, schema: RLMObjectSchema) {
       fatalError("init(realm:schema:) has not been implemented")
   }
   
   required init(realm: RLMRealm, schema: RLMObjectSchema) {
       fatalError("init(realm:schema:) has not been implemented")
   }
   
   required init() {
       fatalError("init() has not been implemented")
   }

上面這三個方法之后,然后run,就會crash了。

解決辦法:去掉你自己自定義的init方法,使用convenience來定義你的init方法
上面的解決方法是:在required前面添加convenience,不知道convenience是干什么的同學(xué),自己去補充swift基礎(chǔ)知識

    convenience required init?(coder aDecoder: NSCoder) {
        self.init()
        self.name = aDecoder.decodeObjectForKey("name") as! String
        self.updated = aDecoder.decodeObjectForKey("updated") as! NSDate
    }

舉一反三:繼承了realm的Object對象之后,我們不需要再自己定義新的init()方法了,但是我們可以使用convenience創(chuàng)建一個便利構(gòu)造器,來方便的根據(jù)我們的需求定義創(chuàng)建init()方法,這也是工廠模式的好處。

關(guān)于realm的更多坑

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容