LoginSignup
8
8

More than 5 years have passed since last update.

Objective-C で変数を取り違えないためのTips

Posted at

以下のコードのおかしいところって、パッと気付かないと思うんです。

SomeView.m
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 2.0, 280, 26.0)];
titleLabel.adjustsFontSizeToFitWidth = YES;
titleLabel.minimumScaleFactor = 0.5;
snippetLabel.text = snippet;
[self addSubview:titleLabel];
self.titleLabel = titleLabel;

UILabel *snippetLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 28.0, 280, 13.0)];
snippetLabel.text = snippet;
snippetLabel.adjustsFontSizeToFitWidth = YES;
snippetLabel.minimumScaleFactor = 0.5;
[self addSubview:snippetLabel];
self.snippetLabel = snippetLabel;

おかしいところは、titleLabelのtextへ代入してそうな部分で、snippetLabelのtextへ代入している部分です。

メソッドを切り分けでば解決するけど、メソッドを切り分けるほど一般的な処理ではない。...というケースは往々にしてあるわけですよね。 じゃあ(Cの)ブロックで囲むことでスコープを切ったら良いんじゃないか、ということで以下。

SomeView.m
{
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 2.0, 280, 26.0)];
    titleLabel.adjustsFontSizeToFitWidth = YES;
    titleLabel.minimumScaleFactor = 0.5;
    snippetLabel.text = snippet;
    [self addSubview:titleLabel];
    self.titleLabel = titleLabel;
}
{
    UILabel *snippetLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 28.0, 280, 13.0)];
    snippetLabel.text = snippet;
    snippetLabel.adjustsFontSizeToFitWidth = YES;
    snippetLabel.minimumScaleFactor = 0.5;
    [self addSubview:snippetLabel];
    self.snippetLabel = snippetLabel;
}

こうすると、snippetLabel.text = snippet;の所でエラーが出るので、見つけやすくなります。

いつでも使えるわけじゃないですが、Tipsとして。

8
8
2

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
8
8