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

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.
主站蜘蛛池模板: 永仁县| 文登市| 宣恩县| 松桃| 青浦区| 根河市| 兰西县| 玉田县| 博野县| 盱眙县| 凤城市| 尼勒克县| 扬州市| 山丹县| 赣榆县| 荥经县| 巫溪县| 漾濞| 怀柔区| 双流县| 灌南县| 兰考县| 库伦旗| 罗定市| 泰宁县| 且末县| 玉树县| 莱芜市| 杭州市| 元阳县| 海淀区| 呼玛县| 阿拉善左旗| 陆河县| 福建省| 安远县| 罗平县| 疏附县| 景德镇市| 耒阳市| 邯郸县|