user7717495
user7717495

Reputation:

save tableview data in swift MVC

I have this code. I'm developing my app without storyboard:

SecondController.swift

class SecondController: UIViewController {

var items: [String] = ["DATA 1", "DATA 2", "DATA 3"]
let tableView: UITableView  =   UITableView()

init(){
    super.init(nibName: nil, bundle: nil)
    self.view = SecondView()
    self.view.backgroundColor=UIColor.green

    tableView.frame         =   CGRect(0, 50, 320, 200);
    tableView.delegate      =   self
    tableView.dataSource    =   self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    self.view.addSubview(tableView)
}

override var prefersStatusBarHidden: Bool {
    return true
}

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

func onClickListener(object : UIButton!) {
    self.navigationController!.popViewController(animated: false)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
}}
extension SecondController: UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
    return self.items.count
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("You selected cell #\(indexPath.row)!")
    items.append("NEW DATA")
    print(items.count)
    self.tableView.reloadData()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    cell.textLabel?.text = self.items[indexPath.row]
    return cell
}}

And SecondView.swift

class SecondView: UIView {
var btnImage = UIButton(image: "resume")

override init(frame: CGRect){
    super.init(frame: screenSize)
    self.backgroundColor = UIColor.black

    // Btn
    self.btnImage.translatesAutoresizingMaskIntoConstraints = false
    addSubview(self.btnImage)
    self.btnImage.alignLeftOfViewVoid(padding: 1)
    self.btnImage.addTarget(self.parentViewController, action: #selector (SecondController.onClickListener(object:)), for: .touchUpInside)

}


required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

deinit{
    self.removeFromSuperview()
}}

The table works perfectly, but when I press the button the app returns to FirstView and FirstController, and when I want return to SecondView and SecondController, I lose the new data items.

Where can I put the array data if I don't want lose them? Can I separate the TableView in another file?

Thank you

Upvotes: 0

Views: 475

Answers (2)

0xNSHuman
0xNSHuman

Reputation: 648

You said you go back to FirstController, so your SecondController gets destroyed from memory along with items array. If you want to have them accessible across the app, you should create a Model class (according to MVC pattern that you mentioned yourself in your question title).

class DataStorage {
    static let shared = DataStorage()
    var items: [String] = ["DATA 1", "DATA 2", "DATA 3"]
}

Now you can access this data from your SecondController like this:

func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
    return DataStorage.shared.items.count
}

This is, of course, rough implementation, and you will most likely need to implement a set of methods in DataStorage class to modify (create, update, delete) your items.

UPD: This way lets you only store data in memory until app is terminated. In order to persist it, you need to store it on disk using CoreData, SQLite, Property Lists etc, as described in article suggested by @f_qi. Anyway, you should have separated Model file like DataStorage to manage this logic.

Upvotes: 1

f_qi
f_qi

Reputation: 699

You did not implement any data persistent method.
Take a look at this link, it shows a couple ways to persist your data.
It's form 2015, so you need to understand it and apply swift 3.1 accordingly.

Upvotes: 0

Related Questions