2015-02-10 38 views
0

我定義爲這樣一個自定義類:檢索數組值與

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中的單個「名稱」值時,我只是一遍又一遍地獲取最後一條記錄。我想我只是不明白如何引用每個條目,因爲它是一個包裝在數組中的類。我相信代碼是問題,這是一遍又一遍地將返回同一行:

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 
    } 

我相信它越來越追加到chosenLocation正確的,但因爲我不知道如何「解包」吧,一個println只會告訴我,我有正確數量的值,而不是其中的值。

非常感謝您爲您提供的任何幫助!

回答

1

它看起來像錯誤是,只是一個單一的位置對象被創建和更新,所以它包含了最後更新

數據移動創作是內for循環...

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

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

@Jawwad提供了一個解決問題的辦法。

請注意,您的代碼不起作用,因爲您要添加到數組的項目是引用類型(類)的實例,所以您要實例化一次,在每次迭代時初始化,然後添加到數組中 - 但添加的內容只是對實例引用的副本,而不是實例本身。

如果您將Location類轉換爲結構,那麼您的代碼就可以正常工作。作爲值類型,結構體按值傳遞,而不是通過引用傳遞,所以將同一實例傳遞給方法的動作會導致創建並傳遞該實例的副本。