UITableViewCell 作为参数不是副本吗?
Is a UITableViewCell as parameter not a copy?
也许现在还为时过早,但我有一小段代码无法理解。
在一个 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 函数中的单元格对象产生影响?单元格不只是一个副本还是我遗漏了一些愚蠢的东西?
我不确定,但我认为是因为 UITableViewCell 是 class。它总是通过引用传递。您正在将 class 的指针传递给函数。
在 Swift class 中是 'reference types' 所以当你将一个 class 的对象传递给一个函数时它不会创建它的新副本而是创建对您拥有的对象的新引用。
这使得修改引用的对象成为可能。
对于对象,我们可以通过引用和值传递。
当你写
let printCell = cell as PrintCell
它是引用,意味着 printCell 不会有新的内存分配,它将指向单元格本身的内存位置。
现在当你执行 printCell 操作时,它会反映在你的视图中,因为这两个对象指向相同的内存位置。
如果您使用 copy 关键字按值分配对象(我不知道如何使用 swift,因为我正在关注 objective-c)。
它将有新的内存位置,当您在 printCell 上执行任何任务时,它不会反映在 Tableview 中。
当您将对象传递给 Swift 中的函数时,它是通过引用传递的。这意味着您正在传递一个指向该对象的指针。在下面的函数中
func configureTestCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath)
cell 是 UITableViewCell 类型的一个实例,因此它是通过引用类型传递的。 "tableView" 函数中的 "cell" 和 "configureTestCell" 中的 "printCell" 指向同一个对象。
也许现在还为时过早,但我有一小段代码无法理解。
在一个 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 函数中的单元格对象产生影响?单元格不只是一个副本还是我遗漏了一些愚蠢的东西?
我不确定,但我认为是因为 UITableViewCell 是 class。它总是通过引用传递。您正在将 class 的指针传递给函数。
在 Swift class 中是 'reference types' 所以当你将一个 class 的对象传递给一个函数时它不会创建它的新副本而是创建对您拥有的对象的新引用。
这使得修改引用的对象成为可能。
对于对象,我们可以通过引用和值传递。 当你写
let printCell = cell as PrintCell
它是引用,意味着 printCell 不会有新的内存分配,它将指向单元格本身的内存位置。
现在当你执行 printCell 操作时,它会反映在你的视图中,因为这两个对象指向相同的内存位置。
如果您使用 copy 关键字按值分配对象(我不知道如何使用 swift,因为我正在关注 objective-c)。
它将有新的内存位置,当您在 printCell 上执行任何任务时,它不会反映在 Tableview 中。
当您将对象传递给 Swift 中的函数时,它是通过引用传递的。这意味着您正在传递一个指向该对象的指针。在下面的函数中
func configureTestCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath)
cell 是 UITableViewCell 类型的一个实例,因此它是通过引用类型传递的。 "tableView" 函数中的 "cell" 和 "configureTestCell" 中的 "printCell" 指向同一个对象。