(Swift) Storing and retrieving Array to NSUserDefaults

前端 未结 7 1011
别跟我提以往
别跟我提以往 2020-11-30 05:43

I am trying to store an array to NSUserDefaults and retrieve the array when needed to populate a UITableView.

Currently I am using:

<
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 06:29

    Here are the way that you can store and retrieved array of object with help of NSKeyArchive.

    To Store array to NSUserDefault.

    let placesData = NSKeyedArchiver.archivedData(withRootObject: placesArray)
    UserDefaults.standard.set(placesData, forKey: "places")
    

    To Retrieved array from NSUserDefault.

    let placesData = UserDefaults.standard.object(forKey: "places") as? NSData
    
    if let placesData = placesData {
        let placesArray = NSKeyedUnarchiver.unarchiveObject(with: placesData as Data) as? [Place]
        print(placesArray)
    }
    

    Hope this help you.

提交回复
热议问题