简体   繁体   中英

Safety way to use [weak self] when using TableViewCell delegate function with closure?

I'm trying to use tableviewcell delegate function with completion closure block.

I concern when I should use [weak self] in this situation.

And I also want to know the better way to implement this kind of logic

What to do this code?

when the user tapped to add new items into stack view

It's going to fetch data from a remote server.

If fetched then let tableviewcell to add new items

protocol myTableViewCellSubViewDelegate {

    func fetchData(cell: MyTableViewCell, completion: @escaping (Bool) -> ())
}


class MyTableViewCell: UITableViewCell {

    var delegate: myTableViewCellSubViewDelegate?

    var stackView = UIStackView()


    func startFetchData(){

        delegate?.fetchData(cell: self){ success in

            if success {
                self.stackView.addArrangedSubview(UIView())

            }
        }
    }
}

Look at startFecthData function in MyTableViewCell..

  1. Should I use [weak self] or not?

  2. in fetchData function, should I @escaping or not?

  3. How about using defer?

Here is MyViewController.swift

 class MyViewController: UIViewController, myTableViewCellSubViewDelegate {

 func doSomthing(url : URL, completion: (Error?) -> ()) {

        completion(nil)

    }

 func fetchData(cell: MyTableViewCell, completion: @escaping (Bool) -> ()) {

        doSomthing(url: URL(string: "www.stackoverflow.com")!) { error in

            if error != nil {
                print("Error...")
            }else {

                completion(true)
            }

        }
    }
}
  1. You should use [weak self] . this will prevent a crash when this cell has been deallocated.

     func startFetchData(){ delegate?.fetchData(cell: self){ [weak self] success in if success { self?.stackView.addArrangedSubview(UIView()) } } } 
  2. Use @escaping, since you run this closure in a different closure.

  3. Don't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM