- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 276字
- 2021-07-02 14:45:08
Dangling references
Now that we've seen the powerful weak and unowned modifiers and have regained control over our memory management, we are thrilled to use it everywhere. That is, until we see a crash in the form of the following:
Fatal error: Attempted to read an unowned reference but object 0x10132c0f0 was already deallocated.
This is the same issue as the, which the dangling pointer one that we saw earlier in this chapter.
Let's reuse the example, as follows:
func getCard() -> Card {
let batman = Person(name: "Batman")
let card = Card(batman)
batman.cards.append(card)
return card
}
let card = getCard()
print("\(card.owner.name)")
In this code, we explicitly return a card, but the owner of this card is not in the memory anymore, as it was properly deallocated after we exited the scope. Let's break it down, line by line, and try to get an idea of the counts, as shown in the following table:

With this in mind, we can now see why the program crashes, as there's nothing left to retain the owner of the card.
This can be seen as unsafe, but it should not be. This example, while valid, is a perfect example where the relationship is unowned because it can't be anything else. weak would have forced us to write the owner as an optional, which is incorrect, and using a strong relationship ultimately leads to cycles and leaks being retained.
To overcome this issue, we have to re-evaluate our code and ensure that we never return a card disassociated from its owner. The unowned references preserve the semantics of your program, while ensuring that the memory management is sane.
- 企業(yè)數(shù)字化創(chuàng)新引擎:企業(yè)級PaaS平臺HZERO
- Python數(shù)據(jù)分析與挖掘?qū)崙?zhàn)
- Python數(shù)據(jù)挖掘:入門、進(jìn)階與實(shí)用案例分析
- 數(shù)據(jù)庫基礎(chǔ)與應(yīng)用:Access 2010
- Python數(shù)據(jù)分析入門:從數(shù)據(jù)獲取到可視化
- Java Data Science Cookbook
- 正則表達(dá)式必知必會
- 醫(yī)療大數(shù)據(jù)挖掘與可視化
- 大數(shù)據(jù)營銷:如何讓營銷更具吸引力
- Python數(shù)據(jù)分析與挖掘?qū)崙?zhàn)(第3版)
- 數(shù)據(jù)庫原理與應(yīng)用
- 編寫有效用例
- Solaris操作系統(tǒng)原理實(shí)驗(yàn)教程
- 爬蟲實(shí)戰(zhàn):從數(shù)據(jù)到產(chǎn)品
- Node.js High Performance