- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 284字
- 2021-07-02 14:45:05
Unowned references
You can use unowned references when you can guarantee that the owner of another object will never exist when the reference is deallocated. Let's look at the following example:
class CreditCard {
let number: String
let expiry: String
unowned let owner: Person
init(owner: Person) {
self.owner = owner
self.number = "XXXXXXXXXXXXXXXX"
self.expiry = "XX/YY"
}
}
class Person {
let name: String
var cards: [CreditCard] = []
init(name: String) {
self.name = name
}
}
In this example, one person can have many credit cards. Each card needs to have an owner, which is immutable.
Let's look that how to use such an API:
let me = Person(name: "John Smith")
let card = CreditCard(owner: me)
let otherCard = CreditCard(owner: me)
me.cards = [card, otherCard]
In this example, me has two credit cards; each card has a back reference to its owner. In this particular case, we can always guarantee that the owner will never be deallocated before the cards. A CreditCard without an owner doesn't make any sense, and if we're trying to access the owner property of such a card, our program is probably not sane anymore. The behavior to notice here is that, compared to the weak modifier, the owner property on the CreditCard is not required to be an optional.
In this particular example, if we omitted the unowned qualifier, when there were no references left to Person, the back references from the cards would keep the object alive, effectively leaking both the credit cards and the owner of the cards.
Now that we've covered the semantics of memory ownership, we can dive deeply into the memory management and debugging tools that come with Xcode.
- 有趣的二進制:軟件安全與逆向分析
- Hands-On Machine Learning with Microsoft Excel 2019
- 算法與數據中臺:基于Google、Facebook與微博實踐
- Mastering Machine Learning with R(Second Edition)
- Spark核心技術與高級應用
- 大數據營銷:如何讓營銷更具吸引力
- 數亦有道:Python數據科學指南
- Starling Game Development Essentials
- 信息學競賽寶典:數據結構基礎
- Spring MVC Beginner’s Guide
- 大數據時代系列(套裝9冊)
- 數據產品經理寶典:大數據時代如何創造卓越產品
- Tableau商業分析從新手到高手(視頻版)
- 大數據用戶行為畫像分析實操指南
- Learning Construct 2