Search code examples
iosswiftuitableviewcore-datansuserdefaults

How can I save data inside a TableView?


In my app I have a label that, when user tap the view o shake the iPhone, it will change the quote in random. If the user double tap the same view, it should save the quote inside a TableView. At the beginning, I thought I could use CoreData, but he didn't work. Now I'm using UserDefaults, And now if I double tap the view, the quote is saved, but only one at time. What I want that to do is that he create a list of all the quotes that a the user double tapped on.

Here's the code inside the doubleTap Object:

let savedQuotes = UserDefaults.standard.setValue(quoteLabel.text!, forKey: "saveQuotes")

    if let printSavedQuotes = UserDefaults.standard.string(forKey: "saveQuotes"){

        print(printSavedQuotes)

    }

And here's the code that I used inside for the TableVIew:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    _ = UserDefaults.standard.string(forKey: "saveQuotes")

    return 15
    
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "QuoteCell", for: indexPath)
    
    if let printSavedQuotes = UserDefaults.standard.string(forKey: "saveQuotes"){
        
        cell.textLabel?.text = "\(printSavedQuotes)"
        
    }

Here's an image of the problem.

Here's an image of the problem


Solution

  • Try as like below approach..

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
        let savedQuotes = UserDefaults.standard.value(forKey: "saveQuotes") as? [String] ?? [String]()
    
        return saveQuotes.count
    
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "QuoteCell", for: indexPath)
    
        let saveQuotes = UserDefaults.standard.value(forKey: "saveQuotes") as? [String] ?? [String]()
    
        cell.textLabel?.text = saveQuotes[indexPath.row]
    
        return cell
    }
    
    func saveQuote(){
    
        var saveQuotes = UserDefaults.standard.value(forKey: "saveQuotes") as? [String] ?? [String]()
    
        saveQuotes.append(quoteLabel.text!)
    
        UserDefaults.standard.set(saveQuotes, forKey: "saveQuotes")
    
        print(saveQuotes)
    }
    

    This is just an example, recommended approach is use sqlite or core-data to store persistent data instead of UserDefaults.