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

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.
主站蜘蛛池模板: 临湘市| 宁远县| 高州市| 雷山县| 六盘水市| 寿宁县| 剑河县| 大同市| 蒙城县| 天峨县| 类乌齐县| 北票市| 鹿邑县| 漳平市| 灵宝市| 浠水县| 渭南市| 唐山市| 嫩江县| 宁阳县| 泽库县| 长子县| 平凉市| 土默特右旗| 峡江县| 南昌县| 平湖市| 肇源县| 云安县| 全椒县| 巴林左旗| 蓬莱市| 清水河县| 腾冲县| 淮南市| 洛隆县| 邵阳县| 高陵县| 阜阳市| 黄平县| 克什克腾旗|