In Objective-C, we can init CADisplayLink with Proxy Pattern to break strong reference:
WeakProxy *weakProxy = [WeakProxy weakProxyForObject:self];
self.displayLink = [CADisplayLink displayLinkWithTarget:weakProxy selector:@selector(displayDidRefresh:)];
Then, just invalidate the displayLink in dealloc
:
- (void)dealloc
{
[_displayLink invalidate];
}
However, NSProxy seems can't be inherited in Swift: https://bugs.swift.org/browse/SR-1715
I tried to write like this:
weak var weakSelf = self
displayLink = CADisplayLink(target: weakSelf!, selector: #selector(displayDidRefresh(dpLink:)))
It didn't work.
I would like to know if there is any way to achieve this like in Objective-C.
An better approach might be to invalidate the display link in
viewWill/DidDisappear
, see alsofor useful information.
If that is not an option: Make the proxy object inherit from
NSObject
instead ofNSProxy
. An Objective-C solution is for example given hereand that can easily be translated to Swift 3:
which can then be used as
Your approach
does not work because it unwraps
weakSelf
when theCADisplayLink
is initialized and passes a strong reference toself
as the target.This proxy class should just work. Don't forget to invalidate before the dealloc.
Usage: