简体   繁体   中英

Swift 3 Saving array with UserDefaults

I am trying to save an array to UserDefaults, but after running the app displays this Error . When the app crashes, Xcode displays correct values of the array, so the data are saved well into the array. I save the string data to array in first VC :

 Last20Times.insert(dsa, at: 0) // Last20Times is the array.
 if Last20Times.count > 0 {
   let defaults = UserDefaults.standard
   defaults.set(Last20Times, forKey: "last20") 

Second controller is TableView:

 if indexPath.section == 1 {
   let ArrayLast20 = UserDefaults.standard.stringArray(forKey: "last20")
   cell.textLabel?.text = ArrayLast20?[indexPath.row]// error(picture)
 }

return cell

Thank you

You need to save your UserDefaults as such:

defaults.synchronize() 

. . .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM