LoginSignup
4

More than 5 years have passed since last update.

循環参照を防ぐためにweak変数に入れて、使う直前でstrong変数に入れるのが面倒くさいのでプリプロセッサマクロで解決する

Last updated at Posted at 2014-05-30

何か既にもっと良いのがあった

weakify/strongify マクロを使うと weak self パターンが簡単に書ける - @uasi

上記の記事で紹介されてる方法の方が良さそうです。

以下、僕の原文

何かブロック使ってると、以下のようなコードが典型的パターンとして出てくるじゃん。

Hoge.m
__weak Hoge *weakSelf = self;
[someObj perform:^{
  Hoge *strongSelf = weakSelf;
  if (strongSelf){
    // your logic
  }
}];

これを、こうすると楽じゃね。 って思った。

Your-Prefix.pch
#define weak_def __weak typeof(self) weakSelf = self;
#define strong_def typeof(self) strongSelf = weakSelf;
Fuga.m
weak_def;
[someObj perform:^{
  strong_def;
  if (strongSelf){
    // your logic
  }
}];

変数名が隠蔽されるのが気に入らんという人は、プリプロセッサマクロに引数入れても良いと思います。 weak_def(mySuperWeak); とか定義できるようにしちゃえば良いかと。 まぁ、メリットが薄れるけど。

ReactiveCocoa入れてると @weakify(self) とか @strongify(self) とか使えるらしいし、じゃあそれ使えばって感じもしますが、Light-Weightな解にも価値があるだとうということで。

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
4