The program duplicate the list on the tableview if I go back from secondviewcontroller

为君一笑 提交于 2019-12-24 07:59:12

问题


I have a viewcontroller with a tableview and with a list of places. If I touch a place from the list, I go to the SecondViewController scene to see more information about the place. But when I go back with the back button, the program duplicate my original list, so the places are two times on the list, then three times, four times... Every time if I go to the SecondViewController and then go back.

Here is my ViewController:

import UIKit

var nev: [String] = []
var cim: [String] = []
var ar: [String] = []


class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var myIndex: Int?

@IBOutlet weak var tableView: UITableView!


override func viewDidLoad() {
    super.viewDidLoad()

    let url = Bundle.main.url(forResource: "pubok", withExtension: "json")
    do {
        let allContactsData = try Data(contentsOf: url!)
        let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
        if let arrJSON = allContacts["Pubok"] as? [[String : Any]] {
            for index in 0...arrJSON.count-1 {

                let aObject = arrJSON[index] as! [String : Any]

                nev.append(aObject["Hely neve"] as! String)
                cim.append(aObject["Cím"] as! String)
                ar.append(aObject["Legolcsóbb sör"] as! String)
            }
        }

        self.tableView.reloadData()
    }
    catch {

    }

}

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

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


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell

    cell.nevLabel.text = nev[indexPath.row]
    cell.arLabel.text = ar[indexPath.row] + "/0.5l"
    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let row = (self.tableView.indexPathForSelectedRow as NSIndexPath?)?.row

    let vc = segue.destination as! SecondViewController

    vc.myIndex = row
}



}

Here is my SecondViewController:

import UIKit



class SecondViewController: UIViewController {

var myIndex: Int?


@IBOutlet weak var secondnevLabel: UILabel!
@IBOutlet weak var secondcimLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    secondnevLabel.text = nev[myIndex!]
    secondcimLabel.text = cim[myIndex!]


}
}

And this is my TableViewCell:

import UIKit

class TableViewCell: UITableViewCell {


@IBOutlet weak var nevLabel: UILabel!
@IBOutlet weak var arLabel: UILabel!




override func awakeFromNib() {
    super.awakeFromNib()

}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

}
}

And this is the main.storyboard


回答1:


The issue is that you have three global arrays, so they persist when you move to the next view controller and they are still around when you go back. Not only are they still around, they have all of the data you put in them the first time you loaded the view. Now, you are going back and appending all of the same data to the arrays, leaving you with twice the data, then three times and so on.

import UIKit

var nev: [String] = []   // Global array declared outside the class
var cim: [String] = []   // Global array declared outside the class
var ar: [String] = []   // Global arrayy declared outside the class

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var myIndex: Int?

The solution

Move those arrays inside your class and pass them along to the next view controller in the same manner that you pass the value of the selected index- by having a corresponding array in the next view controller and assigning its value in prepare(for segue: )

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var nev: [String] = []   // Array is now inside the class
    var cim: [String] = []   // Array is now inside the class
    var ar: [String] = []   // Array is now inside the class

    var myIndex: Int?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let row = (self.tableView.indexPathForSelectedRow as NSIndexPath?)?.row

    let vc = segue.destination as! SecondViewController

    vc.myIndex = row
    vc.nev = nev
    vc.cim = cim
    vc.ar = ar
}

class SecondViewController: UIViewController {

    var myIndex: Int?

    var nev: [String]?
    var cim: [String]?
    var ar: [String]?


来源:https://stackoverflow.com/questions/46025895/the-program-duplicate-the-list-on-the-tableview-if-i-go-back-from-secondviewcont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!