Home Ask Login Register

Developers Planet

Your answer is one click away!

user3708224 February 2016

Reloading and saving items in tableviews

So I am creating a tableview where I add (and delete) items. I am able to add and delete the items in the tableView but...there are some issues...

  1. When I add an item it does not show up in the tableView until I close the simulator, but then when I close and relaunch the app it appears in the tableView.

  2. When I add another item to the tableView and close the app, the old items are replaced by the new added item. So auto-deletes old items when a new item is added to the tableView.

    Naturally I want to save the existing items when I close the app, and I want to add the new items on top of the existing tableView items without having to close the app and relaunch...I am not sure what is wrong with my code...? Thank you in advance!

TableView

import UIKit

class PlaceTableVC : UITableViewController {

var placeList = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    if NSUserDefaults.standardUserDefaults().objectForKey("list")  != nil {
        placeList = NSUserDefaults.standardUserDefaults().objectForKey("list") as![String]

    }

    self.tableView.delegate = self


}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 2
}


// Define number of different cells in the tableview

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if(section == 0) {
        return 1
    }
    else {
        return placeList.count
    }
}


// Define number of different cells in the tableview

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    switch indexPath.section{
    case 0:
        let myProfile = tableView.dequeueReusableCellWithIdentifier("AddAPlaceButton") as! TableViewCell

        return myProfile
    default:
        let cell = tableView.dequeueReusableCellWithIdentifier("AddedPlaceCell        

Answers


Kayron Cabral February 2016

In your class "PlaceTable VC", try putting this function:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.tableView.reloadData()
}

And this function remove viewDidiAppear:

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
    if editingStyle == UITableViewCellEditingStyle.Delete {
        placeList.removeAtIndex(indexPath.row)
        NSUserDefaults.standardUserDefaults().setObject(placeList, forKey: "list")
        tableView.reloadData()
    }
}

Post Status

Asked in February 2016
Viewed 3,579 times
Voted 13
Answered 1 times

Search




Leave an answer


Quote of the day: live life