UserDefaults from Swift Other Screen

Asked 2 years ago, Updated 2 years ago, 97 views

In Swift's UserDefaults

Tab Controller Connected List and Post

Post UserDefaults data does not appear on the list when it is re-launched

What should I do?

Post

import UIKit
import Foundation

class PostVC:UIViewController {

    @IBOutlet weak var textField: UITextField!

    vardata: String = [ ]

    let userDefaults=UserDefaults.standard

    override func viewDidLoad(){
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @ IBAction funcellAdd(_sender:Any){
        guard let list = tabBarController ?.viewControllers ?[0] as ? ListVCelse{
            print("Cannot get listVC from tab bar controller")
            return
        }

        let postText=textField.text???"
        list.data.insert(postText, at:0)

        userDefaults.set(data, forKey: "DataStore")

        userDefaults.synchronize()

        list.tableView?.insertRows(at: IndexPath(row:0, section:0), with:.automatic)
    }

}

List

import UIKit

classListVC:UIViewController, UITableViewDataSource, UITableViewDelegate{

    @IBOutlet weak variableView:UITableView!

    vardata: String = [ ]

    let userDefaults=UserDefaults.standard

    override func viewDidLoad(){
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        // <TableView Initial Configuration>
        tableView.dataSource=self
        tableView.delegate=self

        data=readData()
    }

    functableView(_tableView:UITableView, numberOfRowsInSection section:Int) - > Int{
        return data.count
    }

    functableView(_tableView:UITableView, cellForRowAtindexPath:IndexPath) - >UITableViewCell{
        let postcell=tableView.dequeueReusableCell(withIdentifier: "postcell")!
        postcell.textLabel?.text=data [indexPath.row]
        return postcell
    }

    funcreadData()->[String]{
        let dataArray=userDefaults.array(forKey: "DataStore") as?[String]??[]
        return dataArray
    }

}

swift xcode uikit

2022-09-30 18:11

1 Answers

Class PostVC

@IBAction funcellAdd(_sender:Any){
    guard let list = tabBarController ?.viewControllers ?[0] as ? ListVCelse{
        print("Cannot get listVC from tab bar controller")
        return
    }

    let postText=textField.text???"
    list.data.insert(postText, at:0)

    userDefaults.set(list.data, forKey: "DataStore") // data=>list.data

    userDefaults.synchronize()

    list.tableView?.insertRows(at: IndexPath(row:0, section:0), with:.automatic)
}

Rewrite the line with the comment above.It's a simple mistake.


2022-09-30 18:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.