- 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.
- Hands-On Data Structures and Algorithms with Rust
- 從0到1:數據分析師養成寶典
- 文本挖掘:基于R語言的整潔工具
- Libgdx Cross/platform Game Development Cookbook
- 大數據時代下的智能轉型進程精選(套裝共10冊)
- Spark核心技術與高級應用
- 數據架構與商業智能
- Spark大數據編程實用教程
- Oracle PL/SQL實例精解(原書第5版)
- Oracle RAC日記
- 大數據與機器學習:實踐方法與行業案例
- 商業智能工具應用與數據可視化
- SQL Server 2008寶典(第2版)
- 離線和實時大數據開發實戰
- Cognitive Computing with IBM Watson