Search code examples
iosswiftuserdefaults

UserDefaults saving array of dictionaries


I'm trying to save dictionary into UserDefaults And then I want to fetch data or delete.

class userDefaultsManager {

   static func getAllUsers()->[UserModel]{

       if let all = UserDefaults.standard.array(forKey: "usersKey") as? [Dictionary<String,Any>] {
           return all.map{UserModel.init(dictionary: $0)}
       }
       return []
   }

   static func insertUser(name:String, email:String)->Bool {

        let newUserModel = UserModel.init(name: name, email: email)

        var all = getAllUser()
        all.append(newUserModel)

        UserDefaults.standard.set(all.map{$0.dictionary}, forKey: "usersKey")

        return UserDefaults.standard.synchronize()
    }

    static func deleteUser(email:String)->Bool {

        var all = getAllUser()
        let index = all.index{$0.email == email}

        if index != nil {

            all.remove(at: index!)

            UserDefaults.standard.set(all.map{$0.dictionary}, forKey: "usersKey")
            UserDefaults.standard.synchronize()

            return true

        } else {
            return false
        }
    }
}

class UserModel:NSObject{

    var name: String!
    var email: String!

    init(name:String, email:String) {

        self. name = name
        self. email = email

        super.init()
    }

    init(dictionary:[String:Any]) {

        self.name = ""
        self.email = ""

        super.init()
        self.setValuesForKeys(dictionary)
    }

    var dictionary:[String:Any] {
        return self.dictionaryWithValues(forKeys: ["name","email"]) //Error here
    }
}

The code working on swift 3 but I got error with swift 4 on var dictionary:[String:Any]

here is the error:

implicit Objective-C entrypoint -[Myapp.UserModel name] is deprecated and will be removed in Swift 4

Please any help to fix this will be appreciated.


Solution

  • Your classes inherited from NSObject, and using objc KVC, it was fine for Swift3, because Swift3 assumed all NSObject subclasses as @objc by default, in Swift4 you need to declare your accessors @objc to make them available for obj-c KVC operations. https://forums.developer.apple.com/thread/81789