Reputation: 4891
I am confused between 2 methods to get callback
in my one class from another class.
This is my scenario :
class TableCell: UITableViewCell {
var callBack:(()->())?
}
I want to use this callback
in my controller class. I know these 2 ways :
Method 1:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier", for: indexPath) as! CustomCell
cell.callBack = {[weak self] () in
}
return cell
}
Method 2:
func callBackFunction() {
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier", for: indexPath) as! CustomCell
cell.callBack = callBackFunction
return cell
}
In first method the reference is weak, is it the same for method 2 ? which one is a better approach ? Pleas add proper explanation too.
Upvotes: 2
Views: 234
Reputation: 31675
Before directly choosing one of the mentioned options, we should recognize what is the [weak self]
part is. The [weak self]
called closure capture list; What's the reason of it?! Well, keep in mind that closures in Swift are reference types, whenever you assign a function or a closure to a constant or a variable, you are actually setting that constant or variable to be a reference to the function or closure. Which means that at some point, if you misusing closures in your code, it could leads to retains cycles.
Citing from The Swift Programming Language - Closures:
If you assign a closure to a property of a class instance, and the closure captures that instance by referring to the instance or its members, you will create a strong reference cycle between the closure and the instance. Swift uses capture lists to break these strong reference cycles.
Which means that you have to follow the first approach if you are aiming to use self
in the body of the closure. Using the weak item self in the capture list resolves (prevents) retains cycles, and that's why you would go with the first method.
For more about how it is done, I would highly recommend to check: Automatic Reference Counting, Resolving Strong Reference Cycles for Closures section.
Upvotes: 2