B
B
bushmaks2018-08-01 02:07:57
iOS
bushmaks, 2018-08-01 02:07:57

How to correctly reassign a value in a function and pass it to another class?

Hello, I have a function that is called when clicking on a cell in a TableView.
Function code from TableViewController:

override func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
        CreateTodoTableViewCell().selectedProject = indexPath.row
    }

I want to pass the clicked indexPath.row to another class: CreateTodoTableViewCell
code from CreateTodoTableViewCell class:
class CreateTodoTableViewCell: UITableViewCell {
    
    private var _selectedProject = -1
    
    var selectedProject:Int {
        set {
            _selectedProject = newValue
        }
        get {
            return _selectedProject
        }
    }

    @IBAction func CreateTodoTextField(_ sender: UITextField) {
            TodoListViewController.sharedInstance.Todos[selectedProject].append(sender.text!)
        }
        
    }

The fact is that when I select the cell I need, the function from the controller changes the value, but when I press the done button, the value is restored to the original -1, respectively, and the index -1 is sent to Todos. What is the correct way to reassign the selectedProject value in a function and pass it to another class?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Cherny, 2018-08-01
@bushmaks

First, another method, tableView(_:didSelectRowAt:) , is used to track the click on the cell .
Secondly, as you can see from your code, you don't quite understand how to deal with class instances. That is, when CreateTodoTableViewCell().selectedProject = indexPath.row is done , then an instance (object) of the CreateTodoTableViewCell class is created and some value is assigned to its selectedProject variable . What's next? Further, at the exit from the function, this class is removed from memory, and somewhere else in your code you call a method of another object of the same class, but which has a default selectedProject , -1. You need in the didSelectRowAt methodget your real cell instead of creating it:

if let cell = tableView.cellForRow(at: indexPath) as? CreateTodoTableViewCell {
      cell.selectedProject = indexPath.row
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question