Search code examples
iosswiftrealmnsuserdefaults

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'

Solution

  • 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.