I am facing an error when storing an array in UserDefaults

56 Views Asked by At

Thread 1: "Attempt to insert non-property list object (\n
"VPQuizzy.UserDetails(name: \"Wewewe\", userName: \"Wefrfrferf\", password: \"wedwedwedwed\")"\n) for key userDataList"

struct UserDetails{
    let Name:String
    let userName:String
    let password:String
}

 var userList = [UserDetails]()
 
 
  func setUserData(name:String?,userName:String?,password:String?){
        guard let name = name,let userName = userName,let password = password else{
            print("Please check again the code")
            return
        }
        if let storedUserList = UserData.dictionary(forKey: UserDefaultKey.userDataList.rawValue) as? [UserDetails]{
                    userList = storedUserList
                } else {
                    userList = []
                }
        userList.append(UserDetails(Name: name, userName: userName, password: password))
        print(userList)
        setUserData(userList)
    }
    func setUserData(_ userList:[UserDetails]){
        UserData.setValue(userList, forKey: UserDefaultKey.userDataList.rawValue)
    }
1

There are 1 best solutions below

0
benc On

In this case, I think the error is caused by using array.

A default object must be a property list—that is, an instance of (or for collections, a combination of instances of) NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData.

(emphasis mine)

https://developer.apple.com/documentation/foundation/userdefaults

Besides the recommendation, you might consider using an NSArray (to be honest, I don't know what the tradeoffs are, so that becomes another topic).