In objective c in order to avoid retain cycles when using blocks a weak reference is passed to the block
1
2
3
4
5
|
__weak SomeViewController *weakSelf =
self
;
[
self
performTask:^{
[weakSelf callSomeMethod];
}];
|
In swift we can do something similar
1
2
3
4
5
|
weak var weakReference =
self
performTask() {
weakReference.callSomeMethod()
}
|
Swift has a feature called Captureless that further simplifies managing weak references. Using captureless the code would look like
1
2
3
|
performTask() { [weak
self
] in
self
.callSomeMethod()
}
|
Captureless also allows multiple weak references to be passed to the closure
1
2
3
|
performTask() { [weak
self
, anotherVariableWithWeakReference] in
self
.callSomeMethod()
}
附上链接:http://aryaxt.wordpress.com
|