在NSUserDefaults和Realm中保存对象 [英] Save an object in NSUserDefaults and Realm

查看:65
本文介绍了在NSUserDefaults和Realm中保存对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将对象保存在 NSUserDefaults Realm (快速)中?

Is it possible to save an object in both NSUserDefaults and Realm (Swift) ?

我发现创建模型时遇到了问题,因为 NSUserDefaults 需要继承 NSObject ,而Realm需要继承 Object .

I have found a problem in creating my Model since NSUserDefaults require the inheritance of NSObject and Realm requires the inheritance of Object.

这样做,会引发此错误

Multiple inheritance from classes 'Object' and 'NSObject'

推荐答案

使用Swift4的 Codable 协议,您可以将自定义类保存到 UserDefaults ,而不必遵守旧的 NSCoding 协议.

Using Swift4's Codable protocol, you can save a custom class to UserDefaults without having to conform to the old NSCoding protocol.

class Team: Object, Codable {
    @objc dynamic var id:Int = 0
    @objc dynamic var name:String = ""
}

let team = Team()
team.id = 1
team.name = "Team"
let encodedTeam = try! JSONEncoder().encode(team)
UserDefaults.standard.set(encodedTeam, forKey: "team")
let decodedTeam = try! JSONDecoder().decode(Team.self, from: UserDefaults.standard.data(forKey: "team")!)

这解决了多重继承的问题,因为您的类型不再需要从 NSObject 继承.

This solves the problem of multiple inheritance, since your type doesn't need to inherit from NSObject anymore.

这篇关于在NSUserDefaults和Realm中保存对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆