Kushal Jogi
Kushal Jogi

Reputation: 285

TableView shows duplicate cells on reloading

I want to show the data related to a particular date that is selected from the datePicker in the tableView. But, when I reload the tableView it shows duplicate cells. Here is my code

sessionViewController.swift

import UIKit
class sessionViewController: UIViewController{

@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var datePicker: UIDatePicker!

override func viewDidLoad() {
super.viewDidLoad()
    datePicker.datePickerMode = UIDatePickerMode.Date
    datePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)

    let date = NSDate()
    let formatter = NSDateFormatter()
    formatter.dateFormat = "M/d/yyyy"

    let today = formatter.stringFromDate(date)
    dateLabel.text = today


}

func datePickerChanged(datePicker:UIDatePicker) {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "M/d/yyyy"


    var strDate = dateFormatter.stringFromDate(datePicker.date)
    dateLabel.text = strDate
    Singelton.setTutorDate(strDate)
    NSNotificationCenter.defaultCenter().postNotificationName("load", object: nil)
}

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


}

sessionTableViewController.swift import UIKit

class sessionTableViewController: UITableViewController{
var myData: Array<tutor> = []
var myDummy: Array<String> = []
var date: String!

override func viewDidLoad() {
    super.viewDidLoad()
    println("\(myData)")

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadList:",name:"load", object: nil)

    date = Singelton.getTutorDate()
    myDummy = ["Harsh","Akash","A","B","C","d","e","f","g","h","i","j","k","l","m","n"]
    let cond = AWSDynamoDBCondition()
    let v1    = AWSDynamoDBAttributeValue(); v1.S = date
    cond.comparisonOperator = AWSDynamoDBComparisonOperator.EQ
    cond.attributeValueList = [ v1 ]



    let exp = AWSDynamoDBScanExpression()
    exp.scanFilter = [ "startDate" : cond ]


    self.scan(exp).continueWithSuccessBlock({ (task: AWSTask!) -> AWSTask! in
        NSLog("Scan multiple values - success")
        let results = task.result as! AWSDynamoDBPaginatedOutput
        for r in results.items {


            let myItem: secondItem = r as! secondItem

            let myTutor: tutor = tutor()

            myTutor.setName(myItem.name)
            myTutor.seteMail(myItem.email)
            myTutor.setStartDate(myItem.startDate)
            myTutor.setStartTime(myItem.startTime)
            myTutor.setEndTime(myItem.endTime)
            println(myItem.name)

            self.myData.append(myTutor)
            println("\(self.myData)")

        }
        dispatch_async(dispatch_get_main_queue(), {
            self.tableView.reloadData()
        });
        return nil
    })
}

func loadList(notification: NSNotification){
    //load data here
   // myData.removeAll(keepCapacity: false)
    self.myData.removeAll(keepCapacity: false)
    self.viewDidLoad()
}



func scan(expression : AWSDynamoDBScanExpression) -> AWSTask! {

    let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
    return mapper.scan(secondItem.self, expression: expression)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return myData.count

}


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

    let cellID: String = "cell1"
    var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! timeCell

 //   cell.separatorInset = UIEdgeInsetsZero
//    cell.nameTutor.text = self.myData[indexPath.row].getName() as String
    cell.nameTutor.text = self.myData[indexPath.row].getName() as String
    cell.timeLabel.text = self.myData[indexPath.row].getstartDate() as String
    cell.hourLabel.text = "\(self.myData[indexPath.row].getStartTime())-\(self.myData[indexPath.row].getendTime())"
    return cell
}



override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let indexPath = tableView.indexPathForSelectedRow();
    println("\(indexPath?.row)")


}

Below are the screenshots. When I change the date from datePicker the tableView gets reloaded but the cell gets duplicated.

It would be a great help if someone could suggest me a way out. Thanks }

enter image description here

Upvotes: 0

Views: 2729

Answers (1)

pnavk
pnavk

Reputation: 4642

You shouldn't ever need to call ViewDidLoad manually. Let the View Lifecycle events be called by the framework.

Move your code that populates the myData array into a separate method. Call this method from ViewDidLoad in place of the current logic. Then in your loadData method, call this method again to repopulate your list and reload the table data.

Upvotes: 1

Related Questions