Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Memory Leak #218

Open
moxian1993 opened this issue Mar 20, 2024 · 0 comments
Open

Memory Leak #218

moxian1993 opened this issue Mar 20, 2024 · 0 comments

Comments

@moxian1993
Copy link

这段代码会导致内存泄漏:

let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false)

分析原因如下:

  1. self -> toast: self.addSubview(toast)
  2. toast -> timer: objc_setAssociatedObject(toast, &ToastKeys.timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  3. timer -> self(target): Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false)

可行的解决方案: 使用 weakProxy

// 将原先代码改成:
let weakProxy = WeakProxy(self)
let timer = Timer(timeInterval: duration, target: weakProxy, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false)

// WeakProxy 实现
class WeakProxy: NSObject {
    weak var target: NSObjectProtocol?
    static func proxyWithTarget(target:NSObjectProtocol) -> WeakProxy {
        return WeakProxy.init(target: target)
    }

    init(target:NSObjectProtocol) {
        self.target = target
        super.init()
    }
    
    override func forwardingTarget(for aSelector: Selector!) -> Any? {
        return target
    }
    
    override func responds(to aSelector: Selector!) -> Bool {
        return target?.responds(to: aSelector) ?? false || super.responds(to: aSelector)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant