官术网_书友最值得收藏!

Using weak

Using weak will ensure that we never create a strong reference in ref, but will not retain the objects, either. If the object passed in ref is never retained by any other object, it will automatically be deallocated. This will lead to unexpected behavior, as the chain will be deallocated, and only a returned object will be kept in the memory:

class MemoryLeak {
weak var ref: MemoryLeak?
init(ref: MemoryLeak) {
self.ref = ref
}
init() {
ref = self
}
}

func test() -> MemoryLeak {
let a = MemoryLeak()
let b = MemoryLeak(ref: a)
let c = MemoryLeak(ref: b)
a.ref = c
return a
}

let result = test()
assert(result.ref != nil)

In the preceding code, we changed the MemoryLeak class, in order to keep a weak reference in ref. Unfortunately, the program will crash at the assertion line, as the ref property will be deallocated.

This is often the behavior that you are looking for with delegation. Using weak for the delegate lets you safely avoid thinking about the potential reference cycle; however, the delegates should be retained on their own.
主站蜘蛛池模板: 石柱| 泌阳县| 张家川| 瑞金市| 汶上县| 青浦区| 汾阳市| 繁峙县| 永寿县| 公安县| 图们市| 通州区| 惠来县| 高要市| 德安县| 中西区| 黑水县| 保亭| 常州市| 富源县| 鄂尔多斯市| 嵩明县| 广西| 虎林市| 汝州市| 遂宁市| 温宿县| 调兵山市| 怀宁县| 宝应县| 金华市| 池州市| 威信县| 浪卡子县| 沂水县| 克山县| 淅川县| 年辖:市辖区| 阿鲁科尔沁旗| 衡南县| 海门市|