SwitchCaseの怪

怪というほどのことでもないかw

ネットワーク疎通確認の為に、下記のサイトを参考にしたのだけど、
まったく関係ないところでハマリそうになったのでメモ。

iPhoneアプリケーションで圏外を通知する。 - 24/7 twenty-four seven
Reachabilityがバージョンアップされて使い方が少し変更されていた - tomute's note

Reachabilityというサンプルコード内で、ネットワークの状態でswitch-caseさせている箇所がある。ネットが届かくあなったらUIAlertViewを表示させようとして、[NSNotificationCenter defaultCenter]に登録するコールバックとして以下のようなコードを書いた。

- (void)reachabilityChanged:(NSNotification *)notification {
  NetworkStatus status = [r currentReachabilityStatus];
	
  switch (status) {
    case NotReachable:
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"not reached" message:@"network is down" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
      break;
    default:
      NSLog(@"reached");
      break;
  }
}


これをコンパイルすると、

 error: expected expression before 'UIAlertView'

というメッセージが表示されてしまう。


if文でやると問題なくコンパイルできるので、switch-case内で変数宣言が使えないのかもしれない。
ぐぐってみるとやはりそうだった

http://iphone-dev.ensites.net/archives/474

スコープがあると良いそうなので、以下のように修正。

  switch (status) {
    case NotReachable: {
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"not reached" message:@"network is down" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
      [alert show];
    }
      break;
    default:
      NSLog(@"reached");
      break;
  }

Xcodeではインデントが変www

さて、このコードを実行してみると3回UIAlertViewが表示されてしまう。デバッガコンソールにも3回コールバックが呼ばれているようなログが残っている。

2010-02-07 22:12:27.060 Movapic2[78873:207] Reachability Flag Status: -- ------- networkStatusForFlags
2010-02-07 22:12:27.182 Movapic2[78873:207] Reachability Flag Status: -R tc----- networkStatusForFlags
2010-02-07 22:12:46.256 Movapic2[78873:207] Reachability Flag Status: -R ------- networkStatusForFlags

UIAlertViewを1回だけ表示させる良い方法はないものだろうか。