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

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.
主站蜘蛛池模板: 宣威市| 乌什县| 汶川县| 文登市| 利川市| 博罗县| 阳信县| 遂川县| 郓城县| 江山市| 谢通门县| 南投市| 田东县| 商丘市| 望江县| 铁岭县| 辉县市| 永修县| 周口市| 邢台市| 汝阳县| 凌源市| 河北省| 桃园县| 福建省| 什邡市| 察雅县| 五家渠市| 成武县| 汕头市| 疏勒县| 于田县| 河北省| 女性| 双鸭山市| 稻城县| 南木林县| 明星| 将乐县| 芦溪县| 荆州市|