将方法传递给采用闭包的函数时,我可以使用someFunc(closure: someMethod) or
someFunc() { [unowned self] in self.someMethod() }`。
第一个较短,但提供了强有力的参考。如何在避免这种强引用的同时使用它?
这是一个既有泄漏的演示也有好的演示: https ://swiftlang.ng.bluemix.net/#/repl/581ccd3a0bdc661a6c566347
import Foundation
private var instanceCounter = 0
class Leak : NSObject {
override init() {
super.init()
instanceCounter += 1
}
deinit {
instanceCounter -= 1
}
}
class OnFunctionLeak : Leak {
override init() {
super.init()
_ = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "OnFunctionLeak"),
object: nil,
queue: nil,
usingBlock: doNothing)
}
func doNothing(_ notif: Notification) { }
deinit {
NotificationCenter.default.removeObserver(self)
}
}
class OnClosureLeak : Leak {
override init() {
super.init()
_ = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "OnFunctionLeak"),
object: nil,
queue: nil) { [unowned self] notif in
self.doNothing(notif)
}
}
func doNothing(_ notif: Notification) { }
deinit {
NotificationCenter.default.removeObserver(self)
}
}
var onFunctionLeak: OnFunctionLeak? = OnFunctionLeak()
onFunctionLeak = nil
//XCTAssertEqual(instanceCounter, 0)
print("instanceCounter: \(instanceCounter) == 0")
instanceCounter = 0
var onClosureLeak: OnClosureLeak? = OnClosureLeak()
onClosureLeak = nil
//XCTAssertEqual(instanceCounter, 0)
print("instanceCounter: \(instanceCounter) == 0")
较短的选择在第 26 行,如果我替换doNothing
为{ [unowned self] notif in self.doNothing(notif) }
,则强引用消失了。
有任何想法吗?