1

I have a table that basically loads data coming from backend i.e. Parse. Now after clicking on a cell and processing logic successfully on other view controller (detail controller), I have an unwind segue that is performed automatically. This unwind segue takes us back to the same table. Except when I go back, the same results showing in cells is showing twice (duplication). If I repeat the above process 3 times, I see each record duplicated 3 times and so on.

I read in other posts here that better clear the array, which I did but it seems its not working. Or it could be me clearing it in the wrong place.

Here is the code for viewWillAppear:

 override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        SwiftAddressBook.requestAccessWithCompletion({ (success, error) -> Void in
            if success {
                if let people = swiftAddressBook?.allPeople {
                    let arrayOfArrays = people.flatMap({$0.phoneNumbers?.map( {$0.value})})
                    let finalArray = arrayOfArrays.flatMap({ $0 })
                    self.numbersArray = self.getCleanNumberArrayFromArrayInput(finalArray)
                }

                dispatch_async(dispatch_get_main_queue()) {
                    self.getUsersMatchingNumbers({ (result)->Void in
                        self.userMatchArray = []
                        self.userMatchArray = result
                        self.tableView.reloadData()
                    })
                }
            }
            else {
                //no success. Optionally evaluate error
                print("Access Red")
            }
        })
    }

and this is cellForRowAtIndex:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellIdentifier = "cell"
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ContactTableCell

        let row = indexPath.row

        if(self.userMatchArray.count > 0 )
        {
            cell.name.text = self.userMatchArray[row]["name"] as? String
        }else{
            cell.name.text = "You have no friends yet"
        }


        return cell
    }

Any help sorting this out would be appreciated. Thanks in advance.

Tobi Nary
  • 4,566
  • 4
  • 30
  • 50
ksa_coder
  • 1,393
  • 3
  • 15
  • 38
  • Have you tried to put a break on `self.userMatchArray = result` and see what inside `result` array? – euvs Jan 26 '16 at 11:09
  • @euvs yes now I tried and it shows at first run 6 values then after the unwind segue and coming back to view, it has 12 values. – ksa_coder Jan 26 '16 at 11:13
  • It seems that the problem is not with your `self.userMatchArray`, but rather somewhere else. Try inspecting what your `self.getUsersMatchingNumbers` function does and see where `result` comes from. Or you can post it here and we all have a look at it. @ksa_coder – euvs Jan 26 '16 at 11:21
  • I implemented viewWillDisappear and there I emptied the arrays...seems to work great now – ksa_coder Jan 26 '16 at 11:21
  • 1
    You do now that this is bad practice, Unless you want it to reload the data every time you land on the screen. Your API calls will go through the roof – Devster101 Jan 26 '16 at 13:45
  • @Devster101 am open to better suggestions :) I would really appreciate it – ksa_coder Jan 26 '16 at 13:46
  • 1
    Well for example you move the code to its own function; say fetchData(), then call this function from viewDidLoad. This means it will only run once, and you can click into each cell and unwind without reloading the table each time. If you really needed to reload the data you could implement a pull to refresh action on the table. – Devster101 Jan 26 '16 at 13:51
  • This is happening because the code is in the `viewDidAppear`. every time the user goes back to that `VC` the query happens repetitively. Don't put it in the `viewDidAppear`. @ksa_coder Devster101 is on point as well. – Lukesivi Jan 26 '16 at 13:56
  • Cool...will refactor and fix things around and let you know what happens . Thanks for hints – ksa_coder Jan 26 '16 at 14:01

1 Answers1

0

This is happening because the code is in the viewDidAppear method. Every time the user goes back to that VC the query happens repetitively.

Don't put it in the viewDidAppear.

Adding onto @Devster101's comment, you should create a fetchData function or a UIRefreshControl to handle the events (or something similar).

You can create a refresh function like this:

 var refresher: UIRefreshControl!


  func refresh() {


   //do your query here

    }

And then in the viewDidLoad

override func viewDidLoad() {
        super.viewDidLoad()

        refresher = UIRefreshControl()

        refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")

        refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)

        self.tableView.addSubview(refresher)

        refresh()

    }

This way, you give power to the user.

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done? This question and answer is a good reference as well.

Community
  • 1
  • 1
Lukesivi
  • 2,206
  • 4
  • 25
  • 43