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..
Should I use [weak self] or not?
in fetchData function, should I @escaping or not?
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)
}
}
}
}
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()) } } }
Use @escaping, since you run this closure in a different closure.
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.