“Like a weak reference, an unowned reference does not keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is used when the other instance has the same lifetime or a longer lifetime. You indicate an unowned reference by placing the unowned keyword before a property or variable declaration.”
摘錄來自: Apple Inc. “The Swift Programming Language (Swift 3.1)”廷痘。 iBooks.
Swift中經(jīng)常使用unowned和weak來修飾逃逸閉包中的變量,以避免Strong Reference Cycles;知道這個特性后,心想媽媽再也不怕我寫循環(huán)引用了!F杏薄!
于是有了如下代碼:
private lazy var pendingBadge: JSBadgeView = { [unowned self] in
return JSBadgeView.init(parentView: self.pendingButton, alignment: .topRight)
}()
func updateOrderCount() -> Void {
HTTPSManager.shared().getDataWithActionStr(API_GetOrderCount, params: ["state": "0"], isShowHUD: false, success: { [unowned self] (object: Any?) in
let responseObject = object as? NSDictionary
let countOption = responseObject?.safelyValue(forKey: "retData") as? Int
if let count = countOption, count > 0 {
self.audtingBadge.badgeText = String(count)
} else {
self.audtingBadge.badgeText = nil
}
}, failure: nil)
}
如果你感覺上邊的Swift代碼有些瑕疵,好吧讶迁,有些是從Objective-C橋接過來的?。
上邊代碼看上去沒什么問題核蘸,可是發(fā)過生產(chǎn)才意識到巍糯,unowned有問題!?驮K盥汀!果然打開Bugly一看徙鱼,已經(jīng)有了三五個issue宅楞。
蘋果給的提示:
“Use an unowned reference only when you are sure that the reference always refers to an instance that has not been deallocated.
If you try to access the value of an unowned reference after that instance has been deallocated, you’ll get a runtime error.”
摘錄來自: Apple Inc. “The Swift Programming Language (Swift 3.1)”。 iBooks.
unowned修飾的變量不能保證其一定有值袱吆,它和weak的區(qū)別是不會自動nil化厌衙;如果引用的對象已經(jīng)被釋放掉了,再向其發(fā)送消息就極可能crash杆故。
另外迅箩,不管是OC還是Swift,很多人看到閉包就用weak修飾引用的變量处铛,其實在保證不會造成Strong Reference Cycles的情況下饲趋,保持對象的強引用還是很有必要的拐揭。