Question

I'd like to be able to programatically attribute custom properties to a UITableViewCell (or any other object for that matter)

I'm using a delegate method in Swift w/ Realm.io DB (but I'm guessing it should be something similar in objective-c). Is using commented out line below == correct way of doing this?

override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
    let cell = tableView!.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as Cell

    let object = array[UInt(indexPath!.row)] as Language
    cell.textLabel.text = object.title
    cell.position = object.position // does not produce any warnings
    return cell
}

Attributing title works just fine (because it is a label), but how do I attribute other (non-declared) properties to a cell so I can recover them later, when traversing the tableView?

for var row = 0; row < tableView.numberOfRowsInSection(0); row++ {
    var cellPath = NSIndexPath(forRow: row, inSection: 0)
    var cell:Cell = tableView.cellForRowAtIndexPath(cellPath) as Cell
    println(cell) // This prints out my cells, which contains a .text property, but no custom properties
}

Println produces the following result, but position property is not in it:

<_TtC8Verbum_24Cell: 0x7f9fb58bd3d0; baseClass = UITableViewCell; frame = (0 0; 320 44); text = 'Italiano'; autoresize = W; layer = <CALayer: 0x7f9fb585bb70>>

<_TtC8Verbum_24Cell: 0x7f9fb58bb670; baseClass = UITableViewCell; frame = (0 44; 320 44); text = 'Francais'; autoresize = W; layer = <CALayer: 0x7f9fb58a44f0>>

UPDATE: I'm using a custom class for table cells:

class Cell: UITableViewCell {

    var position:Int?

    init(style: UITableViewCellStyle, reuseIdentifier: String!) {
        super.init(style: .Subtitle, reuseIdentifier: reuseIdentifier)
    }
}
Was it helpful?

Solution

print uses the CustomStringConvertible protocol's description method to print out your object. Since you haven't provided a custom description, you're just seeing the regular UITableViewCell's description. You could simply print(cell.position) or:

var description: String { return "Cell with position \(position)" }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top