简体   繁体   中英

Save an object in NSUserDefaults and Realm

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

I have found a problem in creating my Model since NSUserDefaults require the inheritance of NSObject and Realm requires the inheritance of 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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