简体   繁体   English

在 NSUserDefaults 和 Realm 中保存一个对象

[英]Save an object in NSUserDefaults and Realm

Is it possible to save an object in both NSUserDefaults and Realm (Swift) ?是否可以同时在NSUserDefaultsRealm (Swift) 中保存对象?

I have found a problem in creating my Model since NSUserDefaults require the inheritance of NSObject and Realm requires the inheritance of Object .我在创建模型时发现了一个问题,因为NSUserDefaults需要继承NSObject而 Realm 需要继承Object

Doing so , raised this error这样做,引发了这个错误

Multiple inheritance from classes 'Object' and 'NSObject'

Using Swift4's Codable protocol, you can save a custom class to UserDefaults without having to conform to the old NSCoding protocol.使用 Swift4 的Codable协议,您可以将自定义类保存到UserDefaults而无需遵守旧的NSCoding协议。

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")!)

This solves the problem of multiple inheritance, since your type doesn't need to inherit from NSObject anymore.这解决了多重继承的问题,因为您的类型不再需要从NSObject继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM