0

I have a custom class defined as such:

public class Location {
    var name = String()
    var address = String()
    var place = String()    
}

I'm then populating an Array using that class as follows:

    var chosenLocation = [Location]()
    var locationResult = Location()

//Code to parse data here//

        for result in results! {

            locationResult.name = result["name"] as String
            locationResult.address = "Bogus Address"
            locationResult.place = result["place"] as String
            chosenLocation.append(locationResult)
        }

This all seems to be working fine, but when I try to get the individual "name" value in cellForRowAtIndexPath I just get the last record over and over. I guess I just don't understand how to reference each entry since it's a class wrapped in an array. The code I believe is in question, and which is returning the same row over and over is:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")

        var locationAnswer = Location()
        locationAnswer = chosenLocation[indexPath.row
        cell.textLabel?.text = locationAnswer.name            
        return cell
    }

I believe it's getting appended to chosenLocation correctly, but since I don't know how to "unwrap" it , a println only shows me that I have the correct number of values and not what's in them.

Thanks a bunch for any help you can provide!

2 Answers 2

1

It looks like the bug is that just a single Location object is created and updated, so it contains the data from the very last update

Move the creation to be within the for loop...

// var locationResult = Location() <- Remove this

for result in results! {
    var locationResult = Location() // <- Add it here
    ...
Sign up to request clarification or add additional context in comments.

Comments

0

@Jawwad provided a solution to the problem.

Note that your code doesn't work because the item you are adding to the array is an instance of a reference type (class), so you are instantiating once, initializing at each iteration, then adding to the array - but what's added is just a copy of the reference to the instance, and not the instance itself.

Your code would work just fine if you turn the Location class into a struct. Being value types, structs are passed by value and not by reference, so the action of passing the same instance to the append method results in a copy of that instance to be created and passed.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.