Anmol Rajpal Anmol Rajpal - 3 months ago 10
Swift Question

Json Data not properly reflecting in tableView

Loading local json file to table view and in Debugger Log all goes fine but data is repeating itself in tableView. I've taken screenshot of simulator and Log both here - image description here May be i think i've a problem in appending data. I have TableViewCell - viewCell and my data class - attendance.swift and a tableViewController of course. I am trying to display two data fields. Code for tableViewController -

var checkins = [attendance]()
override func viewDidLoad() {
super.viewDidLoad()
jsonParsingFromFile()
}
func jsonParsingFromFile()
{
let path: NSString = NSBundle.mainBundle().pathForResource("jsonFile", ofType: "json")!
let data : NSData = try! NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMapped)
self.parseJsonData(data)

dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}

func parseJsonData(data:NSData) -> [attendance]{
do{
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
//parse json data

let jsonCheckins = jsonResult?["university1"] as! [AnyObject]
for jsonAttendance in jsonCheckins {

let checkin = attendance()
checkin.id = jsonAttendance["id"] as! Int
checkin.name = jsonAttendance["name"] as! String

if (creden != checkin.id)
{

}
else
{
print(checkin.id)
print(checkin.name)
let check = jsonAttendance["attendance"] as! [AnyObject]

for ch in check {

checkin.subject = ch["subject"] as! String
print(checkin.subject)
checkin.attended = ch["attended"] as! Int
checkin.done = ch["held"] as! Int
checkin.atd = (Float(checkin.attended)/Float(checkin.done))*100
print(checkin.atd , " %")
checkins.append(checkin)
}
}
}
}
catch{
print(error)
}
return checkins
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}

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

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! viewCell
cell.subjectLabel.text = checkins[indexPath.row].subject
cell.attendanceLabel.text = String(checkins[indexPath.row].atd)+" %"
return cell
}

Answer

Error seems to be because you are updating a single object only and adding it to array. Therefore in the end you are left up with only one type of object in array with same values

let checkin = attendance()

move that to inside the loop

for ch in check {