Just My Life & My Work

[Swift] 物件的生與死

作為一個不稱職的 Swift 工程師,偶爾還是要來了解一下物件的生與死

我實在是不太想管底層怎麼管理物件的生與死,只要系統幫我自動處理好,我只想要專心在有趣的商業邏輯上。🙃

直接用 Playground 來跑以下程式。

首先定義貓和球,彼此可以互相擁有⋯⋯

class Cat{
    var name : String
    var age : Int
    var ball: Ball?
    init(name : String, age : Int) {
        self.name = name
        self.age = age
        print("name:\(name), age:\(age) is initialized")
    }
    deinit {
        print("name:\(name), age:\(age) is deinitialized")
    }
}

class Ball{
    var owner : Cat
    init(owner : Cat) {
        self.owner = owner
        print("\(owner.name)'s ball is initialized")
    }
    deinit {
        print("\(owner.name)'s ball is deinitialized")
    }
}

接下來測試貓和球在什麼時機點誕生與死亡。

1.貓與球一起誕生:

var happyCat : Cat? = Cat(name: "Happy", age: 7)
var happyBall : Ball? = Ball(owner: happyCat!)

輸出:

name:Happy, age:7 is initialized

Happy’s ball is initialized

2.貓誕生與死亡:

var happyCat : Cat? = Cat(name: "Happy", age: 7)
happyCat = nil

輸出:

name:Happy, age:7 is initialized

name:Happy, age:7 is deinitialized

3・貓與球(被貓擁有)誕生,但貓死亡:

var happyCat : Cat? = Cat(name: "Happy", age: 7)
var happyBall : Ball? = Ball(owner: happyCat!)
happyCat = nil

輸出:

name:Happy, age:7 is initialized

Happy’s ball is initialized

4・貓與球(被貓擁有)誕生,接著貓與球死亡:

var happyCat : Cat? = Cat(name: "Happy", age: 7)
var happyBall : Ball? = Ball(owner: happyCat!)
happyCat = nil
happyBall = nil

輸出:

name:Happy, age:7 is initialized

Happy’s ball is initialized

Happy’s ball is deinitialized

name:Happy, age:7 is deinitialized

5・貓(擁有球)與球(被貓擁有)誕生,接著貓與球死亡:

var happyCat : Cat? = Cat(name: "Happy", age: 7)
var happyBall : Ball? = Ball(owner: happyCat!)
happyCat?.ball = happyBall
happyCat = nil
happyBall = nil

輸出:

name:Happy, age:7 is initialized

Happy’s ball is initialized

居然貓和球都設為 nil 了,可是貓和球都還沒死!?😳

Reference Cycle 是指物件是由其他物件組成,當被參考的被參考的物件死亡時,我們觀察記憶體實際上卻沒有釋放空間。

可以怎麼解決此 Memory Leak 問題呢?🤔

參考:

隨意留個言吧:)~

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

標籤雲

%d 位部落客按了讚: