We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
这段代码会导致内存泄漏:
let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false)
分析原因如下:
self.addSubview(toast)
objc_setAssociatedObject(toast, &ToastKeys.timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
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) } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
这段代码会导致内存泄漏:
分析原因如下:
self.addSubview(toast)
objc_setAssociatedObject(toast, &ToastKeys.timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false)
可行的解决方案: 使用 weakProxy
The text was updated successfully, but these errors were encountered: