Angel
Angel

Reputation: 49

Problems while making an array and assign elements to a UITableViewCell and get it labelText element back

As title say i have this code:

// Playground - noun: a place where people can play

import UIKit

var placesTableCells:[UITableViewCell] = []
var temporalCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
for i in 0...10 {
    temporalCell?.textLabel?.text = "ola k ace \(i)"
    placesTableCells.append(temporalCell!)
    println(placesTableCells[i].textLabel!.text!)
}
println()
for i in 0...10 {
    println(placesTableCells[i].textLabel!.text!)
}

All works fine when i request placesTableCells within the for loop, it prints:

ola k ace 0
ola k ace 1
ola k ace 2
ola k ace 3
ola k ace 4
ola k ace 5
ola k ace 6
ola k ace 7
ola k ace 8
ola k ace 9
ola k ace 10

But when i request the array out of it it just return "ola k ace 10" ten times, it prints:

ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10
ola k ace 10

Where is the problem there?

Upvotes: 0

Views: 45

Answers (1)

Rajeev Bhatia
Rajeev Bhatia

Reputation: 2994

I believe the reason for that is that you have declared temporalCell outside your for loop and you keep changing it's value everytime in the loop which also changes the value of the previous reference objects in the array.

If you wish to add distinct objects in the array, move your temporalCell declaration in the for loop as such

var placesTableCells:[UITableViewCell] = []
for i in 0...10 {
    var temporalCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
    temporalCell.textLabel?.text = "ola k ace \(i)"
    placesTableCells.append(temporalCell)
    println(placesTableCells[i].textLabel!.text!)
}
println()
for i in 0...10 {
    println(placesTableCells[i].textLabel!.text!)
}

And it should work. Let me know.

Upvotes: 1

Related Questions