Is a UITableViewCell as parameter not a copy?

放肆的年华 提交于 2019-12-12 04:48:58

问题


Maybe it's just too early for now but I got a little piece of code I can't follow.

In a UITableViewController is the following

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = printTable.dequeueReusableCellWithIdentifier("printCell", forIndexPath: indexPath) as UITableViewCell
    configureTestCell(cell, atIndexPath: indexPath)

    return cell;
}

The configureTestCell function:

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])"
    }
}

So my problem and question here is, why are the changes made in printCell have an effect on the cell object in the tableView function? Isn't the cell just a copy or am I missing something stupid-easy?


回答1:


For objects we can pass it by reference and by value. When you write

let printCell = cell as PrintCell

Its by reference, means printCell will not have new memory allocation, it will point to memory location of cell itself.

Now when you perform operation of printCell it will be reflected in your view, As the both objects point to the same memory location.

If you assign object by value using copy keyword (I don't know how to do it with swift as I am following objective-c).

It will have new memory location and when you perform any task on printCell it will not reflected in Tableview.




回答2:


I am not sure but i think is because UITableViewCell is a class. It always passed by reference. You are passing a pointer of the class to the function.




回答3:


In Swift classes are 'reference types' so when you pass an object of a class to a function it does not create a new copy of it but rather creates and new reference to the object you have.

This makes it possible to modify the referenced object.




回答4:


When you are passing a object to a function in Swift it is passed by reference. That mean you are passing a pointer to the object. In the following function

func configureTestCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath)

cell is an instance of type UITableViewCell so it is passed by refernce type. The "cell" in "tableView" function and "printCell" in "configureTestCell" are pointing to the same object.



来源:https://stackoverflow.com/questions/29407813/is-a-uitableviewcell-as-parameter-not-a-copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!