Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Populate prototype cells with values from Array

Hi Guys

So I've been playing around with a few things and I'm stuck (again). I think this is partly due to me not fully understanding some of the code I've used - but I'm getting there... slowly.

I have an array in a struct that contains some values

e.g. var toDoItemsArray = ["Buy Milk","Fix Cupboard","Write Blog"]

I then use that array to populate a Prototype Cell with the values in that array.

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    return manageItems.getNumberOfItems()
}

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
    var cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "toDoItemCell")
    cell.textLabel?.text = manageItems.toDoItemsArray[indexPath.row]
    return cell
}

This all works well. Each time the app launches, the cells are populated.

My issue comes in where I then try add something to the array - I have checked and the new addition to the array is added correctly, but I'm not sure how to get the above two functions to run again so that the prototype cells update again.

If anyone could just point me in the right direction to get this to run, I'd really appreciate it.

1 Answer

Stone Preston
Stone Preston
42,016 Points

whenever you update your data source, just call the reloadData method on your tableView:

tableView.reloadData()

that will cause all the delegate methods to be called again.

also looking at your code for numberOfRows:

you have:

    return manageItems.getNumberOfItems()

but shouldnt you have

    return manageItems.toDoItemsArray.count

i guess maybe your getNumberOfItems method might return the count of that array?