0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

クラスのメモリ管理

Posted at

Swiftはクラスのメモリ管理にARCという方式を採用しています。

ARCでは、インスタンスが初めて生成された時に参照カウントが1になり、以降そのインスタンスへの参照が増えると参照カウントがインクリメントされ、減るとデクリメントされます。そして、参照カウントが0になると、インスタンスも自動的に破棄されます。

デイニシャライザ

class クラス名 {
    deinit {
        クリーンアップなどの終了処理
    }
}

ARCによってインスタンスが破棄されるタイミングで、クラスのデイニシャライザが実行されます。
初期化は一番最初に呼ばれるイメージですが、デイニシャライザはメモリがすべて開放された後の一番最後に呼ばれるというイメージです。なので、デイニシャライザの中にはクリーンアップなどの終了処理を実装します。

値の比較と参照の比較

class SomeClass: Equatable {
    static func ==(lhs: SomeClass, rhs: SomeClass) -> Bool {
        return true
    }
}

let a = SomeClass()
let b = SomeClass()
let c = a

// 値は同じ
a == b // true

// 参照先は別
a === b // false

// aとcの参照先は同じ
a === c // true

参照先の値の比較と、参照先の比較は別になります。
値比較は==, 参照先比較は===を使用します。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?