UITableViewCell作为参数不是副本?
也许现在还为时过早,但是我得到了一些我无法遵循的代码。
在一个UITableViewController是以下
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = printTable.dequeueReusableCellWithIdentifier("printCell", forIndexPath: indexPath) as UITableViewCell configureTestCell(cell, atIndexPath: indexPath) return cell; }
configureTestCell函数:
func configureTestCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let printCell = cell as PrintCell if (self.searchActive) { printCell.nameLabel.text = "Project \(filteredData[indexPath.item])" } else { printCell.nameLabel.text = "Project \(printData[indexPath.item])" } }
所以我的问题和问题是,为什么在printCell中所做的更改会影响tableView函数中的单元格对象? 细胞不是一个副本,还是我错过了一些愚蠢的事情?
对于对象,我们可以通过引用和值来传递它。 当你写
let printCell = cell as PrintCell
它通过引用意味着printCell不会有新的内存分配,它会指向单元本身的内存位置。
现在,当您执行printCell的操作时,它将反映在您的视图中,因为这两个对象指向相同的内存位置。
如果你通过使用copy关键字赋值对象(我不知道如何用swift来完成,因为我跟随着objective-c)。
它将有新的内存位置,当您在printCell上执行任何任务时,它将不会反映在Tableview中。
我不知道,但我认为是因为UITableViewCell是一个类。 它总是通过引用传递。 您正在将该类的指针传递给该函数。
在Swift类中是“引用types”,所以当你将一个类的对象传递给一个函数时,它不会创build它的一个新的副本,而是创build一个新的对你所拥有的对象的引用。
这使得修改引用的对象成为可能。
当你传递一个对象到一个函数在Swift中时,它是通过引用传递的。 这意味着你正在传递一个指向对象的指针。 在下面的函数中
func configureTestCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath)
cell是UITableViewCelltypes的一个实例,所以它被引用types传递。 “tableView”函数中的“cell”和“configureTestCell”中的“printCell”指向同一个对象。