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

Weak references

With weak references, you can safely store a reference to another object without increasing its retain count. This prevents creating cycles with all of the required safety. The weak references are always wrapped into Optionals and, unlike unowned references, when a weak reference gets deallocated, you can safely access it through the Optional interface and check that the object is still set and present at runtime:

class Task {
let description: String
weak var worker: Worker?
init(description: String) {
self.description = description
}
}

class Worker {
var name: String
var currentTask: Task?
init(name: String) {
self.name = name
}
}

let worker = Worker(name: "John Snow")
let task = Task(description: "Night's Watch Commander")
worker.currentTask = task
task.worker = worker

// John snow is the night watch's commander

worker.currentTask = nil

// the task will be deallocated

主站蜘蛛池模板: 宜州市| 封丘县| 故城县| 卫辉市| 章丘市| 吉林省| 宁安市| 厦门市| 嫩江县| 德惠市| 金昌市| 洛宁县| 乐东| 大名县| 望城县| 东港市| 平凉市| 浮梁县| 吉林省| 东乡县| 天津市| 保靖县| 宜宾县| 博爱县| 茂名市| 澄迈县| 银川市| 浮梁县| 长葛市| 防城港市| 张掖市| 怀安县| 大渡口区| 财经| 柳林县| 栾川县| 杨浦区| 上杭县| 厦门市| 钦州市| 株洲县|