Swift での dealloc 質問する

Swift での dealloc 質問する

ビュー コントローラの寿命の終わりに、通知を削除するなどのクリーンアップを実行したいと思いますNSNotificationCenter。実装すると、deallocSwift コンパイラ エラーが発生します。

Cannot override 'dealloc' which has been marked unavailable

Swift でオブジェクトの寿命の終わりにクリーンアップを実行するための推奨される方法は何ですか?

ベストアンサー1

deinit {
    // perform the deinitialization
}

からSwift ドキュメント:

デイニシャライザは、クラス インスタンスが割り当て解除される直前に呼び出されます。デイニシャライザは、init キーワードを使用して初期化子を記述するのと同様に、deinit キーワードを使用して記述します。デイニシャライザはクラス型でのみ使用できます。

Typically you don’t need to perform manual clean-up when your instances are deallocated. However, when you are working with your own resources, you might need to perform some additional clean-up yourself. For example, if you create a custom class to open a file and write some data to it, you might need to close the file before the class instance is deallocated.

おすすめ記事