Created
February 27, 2018 22:01
-
-
Save creaaa/75d7938a29a6ac8a4a86bef2cb3e6895 to your computer and use it in GitHub Desktop.
メソッドにはキャプチャリスト使えない、関数型にはweakを指定できない。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Animal { | |
var f: (() -> Void)! | |
func bark() { | |
// インスタンスをキャプチャして、わざとメモリリークさせる | |
print(self) | |
} | |
deinit { print("deinit!!") } | |
} | |
do { | |
let animal = Animal() | |
animal.f = animal.bark // メソッド(=クロージャの一種)のおすそ分けだ | |
// この記法は、普通に考えて絶対にメモリリークするので危険、 | |
// こんなコード書かないこと | |
} | |
print("done!!") // ここで "deinit" が出力されてない! 循環参照! | |
/* | |
今日は 「もう1つの」解決法を試してみたい | |
1. [weak self] => ふつうの解決方法 | |
と思いきや、メソッドには キャプチャリスト 書けないんやな。 | |
かつ、もう一個、発見した。 | |
ふだんの メソッドは、理論的に見れば 「ふつーに循環参照してる」 | |
(インスタンス -> メソッド(クロージャ), メソッド -> インスタンス(self) ) | |
にもかかわらず、メモリリークにならないのは... | |
とりあえず、「インスタンス -> メソッド への参照」は、 | |
「参照カウントを+1しない」って理解にしておきます...。 | |
2. weak var f と、こっちをweakにすることで解決可能!? | |
=> 「weakは Class or Class Bound Protocolのみ」と言われて撃沈しました | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment