motolog

Everything I love in my life.

Local declaration "button" hides instance variable エラーの原因

iOS開発はじめてまだ1週間ほどで、Xcodeのエラーメッセージやワーニングの意味を把握するのに苦労している今日このごろです。

さて、今回ハマったのは、

local declaration "x" hides instance variable

というもの。

// ViewController.m

@implementation ViewController

- (void) viewDidLoad
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"Touch me!" forState:UIControlStateNormal];
    ...
}

@end

というように button というインスタンスを生成して使用してみると、

local declaration "button" hides instance variable

とワーニングが。

ググってみると、stackoverflow先生に答えがありました。
iphone - Local Declaration "x" hides instance variable xcode warning - Stack Overflow

解説を一部入れ替えると以下のようになります。

This means the variable button is named the same as something else in your class implementation. If you mean to use that variable, drop the UIButton* type declaration off the first line; otherwise, change the name button everywhere it appears in that method.

つまり原因は、

ということで、解決策としては、

  • その名前の変数を使いたいのなら、"UIButton *button"という宣言を消してしまう
  • インスタンス変数の名前を変えてしまう

ということでした。

初歩的ですがメモ。

© 2018 Motoki Yoshida