save and retrieve array to user default using swift

早过忘川 提交于 2019-12-13 10:08:14

问题


I want to save array from json to user default, I'll get the array when I print it. When I retrieve it in different view controller I only get the last array. So how to retrieve all data user default in different view controller.

This is how I save my code in user default

first view controller

let kode_pelaksanaan = item["kode_pelaksanaan"].string
UserDefaults.standard.set(kode_pelaksanaan, forKey: "kode_pelaksanaan")

output:

kode_pelaksanaan : ELR2018120005
kode_pelaksanaan : ELR2018120004
kode_pelaksanaan : ELR2018120003
kode_pelaksanaan : ELR2018120001
kode_pelaksanaan : ELR2018050004

retrieve it in second view controller

let data = UserDefaults.standard.object(forKey: "kode_pelaksanaan")

let parameter =  [
            "request" : "{\"requestMethod\":\"detail_selflearning\",\"user\":\"\(user)\",\"kode_pelaksanaan\":\"\(data ?? "0")\"}"
        ]

output retrieve

kode_pelaksanaan : ELR2018050004

i want output second view controller

kode_pelaksanaan : ELR2018120005
kode_pelaksanaan : ELR2018120004
kode_pelaksanaan : ELR2018120003
kode_pelaksanaan : ELR2018120001
kode_pelaksanaan : ELR2018050004

回答1:


Your code snippet doesn't provide enough information.

Here is an example of how array is stored & retrieved from the UserDefaults

var myArray = [0,1,2]

override func viewDidLoad()
{
    super.viewDidLoad()
    UserDefaults.standard.set(myArray, forKey: "yourArray")

    let data = UserDefaults.standard.object(forKey: "yourArray")!
    print(data)
}



回答2:


Use like this:

    // To save array in UserDefault
    let names = ["John", "Alex", "Matien", "Flex"]
    UserDefaults.standard.set(names, forKey: "names")

    // To get names array from UserDefault safely.
    if let allNames = UserDefaults.standard.object(forKey: "names") as? [String] {
        print(allNames)
    }



回答3:


UserDefaults+Wrapper

    final class UDWrapper {
        class func setArray(key: String, value: NSArray) {
            setObject(key: key, value: value)
        }

        class func getArray(key: String) -> [Any]? {
            return UserDefaults.standard.array(forKey: key)
        }

    class func setObject(key: String, value: Any?) {
        if value == nil {
            UserDefaults.standard.removeObject(forKey: key)
        } else {
            UserDefaults.standard.set(value, forKey: key)
        }
    }
}

usage

  let array: NSArray = ["Hello, World!", 42]
  UDWrapper.setArray(key: "myarray", value: array)

  print(UDWrapper.getArray(key: "myarray") ?? "")


来源:https://stackoverflow.com/questions/53826138/save-and-retrieve-array-to-user-default-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!