0

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'
picciano
  • 22,341
  • 9
  • 69
  • 82
Marwen Doukh
  • 1,946
  • 17
  • 26
  • Why do you want to save it in this way? Save the value in the NSUserDefaults within the variable in object realm ex `myobject.id = NSUserDefaults.standardUserDefaults().objectForKey("id") as Int` – a.masri Apr 19 '18 at 16:17
  • See this answer to save `Swift` object to `UserDefaults` https://stackoverflow.com/a/48438338/4644528 – Kazi Abdullah Al Mamun Apr 19 '18 at 16:52

1 Answers1

3

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.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116