使用class从Array中检索值

时间:2015-02-10 04:11:27

标签: swift

我有一个定义的自定义类:

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

然后我使用该类填充数组,如下所示:

    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)
        }

这一切似乎都运行良好,但是当我尝试在cellForRowAtIndexPath中获取单个“name”值时,我只是反复获取最后一条记录。我想我只是不明白如何引用每个条目,因为它是一个包含在数组中的类。我相信的代码是有问题的,并且反复返回相同的行是:

    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
    }

我相信它会正确地附加到selectedLocation,但由于我不知道如何“展开”它,println只显示我有正确数量的值而不是它们中的内容。

非常感谢您提供任何帮助!

2 个答案:

答案 0 :(得分:1)

看起来这个bug只是创建和更新了一个Location对象,所以它包含了最后一次更新的数据

将创建移动到for循环中......

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

for result in results! {
    var locationResult = Location() // <- Add it here
    ...

答案 1 :(得分:0)

@Jawwad提供了解决问题的方法。

请注意,您的代码不起作用,因为您要添加到数组的项是引用类型(类)的实例,因此您要实例化一次,在每次迭代时初始化,然后添加到数组 - 但是什么是added只是实例引用的副本,而不是实例本身。

如果将Location类转换为结构,则代码可以正常工作。作为值类型,结构是按值而不是通过引用传递的,因此将同一实例传递给append方法的操作会导致创建并传递该实例的副本。

相关问题