【问题标题】:Array is not saving when the app relaunches. Problem with persistent data应用程序重新启动时数组未保存。持久数据的问题
【发布时间】:2019-04-15 18:02:14
【问题描述】:

我正在尝试保存一个数组,但每当我重新加载应用程序时,该数组都是空的。

我已经尝试过 userDefaults 和 core Data。每次我构建一个数组时,它都会在我加载应用程序时开始为空。我不确定将数组保存在哪里以及是否通过 IBAction 添加到数组会导致问题

firstArray: [Double] = []
@IBAction func userSubmit(_ sender: Any) {
oneArray()
func oneArray(){

    if selected == "Breakfast" {



    if let firstArrays = Double(glucoseReading.text!) {

        //append new element to  Array
        firstArray.append(firstArrays)
        print(breakfastSugarsArray)
  }
}
}  

我希望能够在应用程序重新启动时保存数组,并且每次加载应用程序时都不让数组开始为空。我的问题可能是我不知道在哪里保存数组,或者如何保存。

我希望能够在应用重新启动时保存数组,而不是每次加载应用时数组都开始为空。

【问题讨论】:

    标签: arrays swift save persistence


    【解决方案1】:

    每次触发userSubmit(...) 时,它都会检查selected 的值,如您的示例中那样,检查glucosReading.text 中是否有一些Double 数据,然后检索保存在UserDefault 中的数组并更新它使用新值。

    @IBAction func userSubmit(_ sender: Any) {    
       if selected == "Breakfast" {
           if let glucoseData = Double(glucoseReading.text!) {
               // retrieve from UserDefault if none create an empty array
               let glucoseListData = UserDefaults.standard.array(forKey: "glucoseListData") as? [Double] ?? [Double]()
    
               // store in UserDefault
               glucoseListData.append(glucoseData)
               UserDefaults.standard.set(glucoseListData, forKey: "glucoseListData")
    
               // check print outputs in Xcode logs
               println("Glucose data list: \(glucoseListData)")
           }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多