Вы должны переопределить метод инициализации по умолчанию.Почему вы не храните весь словарь вместо создания нескольких свойств.Здесь проверьте мой код, сделанный с Data class.У вас отсутствует метод init, и это может быть проблемой.
convenience init(userDictionary:Dictionary<String, Any>) {
self.init()
if let profile_pic = userDictionary["profile_pic"] {
mProfile_pic = profile_pic as? String
}
if let salutation = userDictionary["salutation"] {
mSalutation = salutation as? String
}
if let status = userDictionary["status"] {
mStatus = status as? String
}
if let title = userDictionary["title"] {
mTitle = title as? String
}
if let uid = userDictionary["uid"] {
mUid = uid as? String
}
}
Sample.swift
import Foundation
import RealmSwift
class Sample: Object {
// Specify properties to ignore (Realm won't persist these)
// override static func ignoredProperties() -> [String] {
// return []
// }
private(set) dynamic var sectionName = ""
private(set) dynamic var data = Data()
/**
Override Object.primaryKey() to set the model’s primary key. Declaring a primary key allows objects to be looked up and updated efficiently and enforces uniqueness for each value.
*/
override static func primaryKey() -> String? {
return "sectionName"
}
convenience init(sectionName: String, data: Data) {
self.init()
self.sectionName = sectionName
self.data = data
}
}
//MARK: DATABASE CODE
func saveData(data:Data, sectionName:String) -> Void {
let obj = Sample(sectionName: sectionName, data: data)
let realm = try! Realm()
try! realm.write({
// If update = true, objects that are already in the Realm will be
// updated instead of added a new.
realm.add(obj, update: true)
})
}
func deleteData(sectionName:String){
let realm = try! Realm()
let data = realm.object(ofType: Sample.self, forPrimaryKey: sectionName)
if data != nil{
try! realm.write {
realm.delete(data!)
}
}
}
func getData(sectionName:String,completion: @escaping (_ Data: Data, _ isContain:Bool) -> Void){
let realm = try! Realm()
let data = realm.object(ofType: Sample.self, forPrimaryKey: sectionName)
if data != nil{
completion((data?.data)!, true)
}else{
completion(Data(), false)
}
}
Пример использования
self.deleteData(sectionName:"primary key")
self.saveData(data: result, sectionName:"primary key")
self.getData(sectionName: "primary key") { (data, isAvailable) in
if isAvailable {
}
}