LoginSignup
9

More than 5 years have passed since last update.

ARCではオブジェクトのスタック変数がnil初期化される

Posted at

ARCの場合ローカルで宣言したオブジェクトのスタック変数はnil初期化される(環境はXcode4.6.3デフォルトのApple LLVM compliler 4.2)。

調べてみるとAppleの日本語リファレンスObjective-Cによるプログラミングのp41"nilの取り扱い"では、ローカル変数のオブジェクトがnil初期化されると記述されている。

初期値を指定しなければ、コンパイラが自動的に、nilに初期化するからです。
XYZPerson *somePerson;
//somePersonの値は自動的にnilになる

また、Transitioning to ARC Release NotesのStack Variables Are Initialized with nilの項目にはstrong,weak, autoreleaseingを使用した場合にnil初期化されるとある。

Using ARC, strong, weak, and autoreleasing stack variables are now implicitly initialized with nil. For example:

ローカルで宣言されるオブジェクトは暗黙的にstrongなのでnil初期化されるのは仕様通りとなるが、下記のように__unsafe_unretainedにして試してみると

- (void)myMethod {
    NSString __unsafe_unretained *name ;
    NSLog(@"name %@",name); //nil初期化されている
}

やはりこれもnil初期化される。__unsafe_unretainedにした場合、仕様に明記されていないがコンパイラが自動的にnil初期化してくれるということなんだろうか。

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
9