簡體   English   中英

當應用程序再次啟動時(Swift),我如何加載存儲在數組中的所有數據?

[英]How can I load all the data stored in the array, when the app starts again (Swift)?

我必須實現一個 function,它在應用程序啟動時將存儲的數據加載到購物清單數組中,以及一個 function,它在按下按鈕時存儲我的列表的當前內容。 我使用UserDefaults class,它適用於第二個 function(按下按鈕時),但不適用於第一個(應用程序啟動時)。 如果我重新啟動應用程序並按下按鈕,我會看到只存儲了最后一次輸入。 如果我想存儲數組中的所有數據,我該如何修復代碼?

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var inputEntered: UITextField!

    // keyboard gives up the first responder status and goes away if return is pressed

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        inputEntered.resignFirstResponder()
        return true
    }

    var shoppingList: [String] = []

    @IBAction func buttonAddToList(_ sender: UIButton) {
        if let item = inputEntered.text, item.isEmpty == false { // need to make sure we have something here
            shoppingList.append(item) // store it in our data holder
        }
        inputEntered.text = nil // clean the textfield input

        print(shoppingList.last!) // print the last element to avoid duplicates on the console

        storeData()
    }

    // this function stores the current contents of my list when the button is pressed

    func storeData () {
        let defaults = UserDefaults.standard
        defaults.set(inputEntered.text, forKey: "Saved array")
        print(defaults)
    }

    // to call the function storeDate(), when the app restarts 

    override func viewDidLoad() {
        super.viewDidLoad()
        inputEntered.delegate = self
        // Do any additional setup after loading the view.
        storeData()
    }
}

您可以向數組添加一個 getter 和一個 setter,並將您的值保留為用戶默認值。 這樣您就不需要調用 storeData 和/或記住在初始化數組時加載數據:

var shoppingList: [String] {
    get {
        UserDefaults.standard.stringArray(forKey: "shoppingList") ?? []
    }
    set {
        UserDefaults.standard.set(newValue, forKey: "shoppingList")
    }
}

您在 viewDidLoad 中調用storeData() ,但 inputEntered 為空,因此您存儲的是空白數據。

此外, defaults.set(inputEntered.text, forKey: "Saved array")不會將 append 新數據添加到密鑰上——它會覆蓋現有數據。 所以你不存儲數組,你只存儲最后一個值。

您需要存儲shoppingList來存儲數組。

我不確定我是否得到了你想要的東西,但你是否嘗試過查看 UITextFieldDelegate。

如果你添加這個,它將確保添加協議,我確信當用戶完成編輯文本字段時可以調用一個方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM