0

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?

Angel
  • 29
  • 6

1 Answers1

1

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.

Rajeev Bhatia
  • 2,974
  • 1
  • 21
  • 29
  • yes it worked very fine, but i can't understand it at all, since im doing append it should add a new object to the array and not mess with the another objects? – Angel Oct 31 '14 at 06:15
  • Thanks for accepting as answer! The basic problem is that even though you are appending the object everytime, you are appending the same object after changing the value which means that even the objects at the previous index in the array which are basically references to your master object have their values changed. Read up on "Classes are reference types" here https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_145 and value types vs reference types in OOLs in general :) – Rajeev Bhatia Oct 31 '14 at 06:20
  • ohh i got it, then basically what i did was make an object and then refer it in all 11 array elements, is there a way to tell the compiler to copy the class object instead of reference it? – Angel Oct 31 '14 at 06:47
  • Check out copyWithZone http://stackoverflow.com/questions/20072729/how-can-i-make-a-deep-copy-in-objective-c – Rajeev Bhatia Oct 31 '14 at 07:15