1

小さな問題があります。私は iPhone プログラミングの初心者なので、答えが明らかな場合はご容赦ください。

現在の料金を見つけたので、アプリの実行中に継続的に更新したいと考えています。私はこれを試しました:

- (void) viewWillAppear:(BOOL)animated
{

 NSLog(@"viewWillAppear");
 double level = [self batteryLevel];
 currentCharge.text = [NSString stringWithFormat:@"%.2f %%", level];
 timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:selfselector:@selector(updateBatteryLevel:) userInfo:nil repeats:NO];
 [super viewWillAppear:animated];
}

最初は正しく読み取り値を取得していますが、更新されていません。どんな助けでも大歓迎です!

どうもありがとう、

スチュアート

4

1 に答える 1

7

上記のコードが継続的に更新されると期待するのはなぜですか?ビューが表示されたら、値を1回設定します。継続的に更新する場合は、バッテリーステータスの更新を登録し、変更されたときにテキストを再描画する必要があります。

あなたbatteryLevelupdateBatteryLevel:ルーチンのコードを見なければ、あなたが何をしているのか、なぜそれらがうまくいかないのかを実際に知る方法はありません。そうは言っても、私はこれにタイマーイベントを使用しないでしょう、それはかなり非効率的です。代わりにKVOを使用します。

- (void) viewWillAppear:(BOOL)animated {
  UIDevice *device = [UIDevice currentDevice];
  device.batteryMonitoringEnabled = YES;
  currentCharge.text = [NSString stringWithFormat:@"%.2f", device.batteryLevel];
  [device addObserver:self forKeyPath:@"batteryLevel" options:0x0 context:nil];
  [super viewWillAppear:animated];
}

- (void) viewDidDisappear:(BOOL)animated {
  UIDevice *device = [UIDevice currentDevice];
  device.batteryMonitoringEnabled = NO;
  [device removeObserver:self forKeyPath:@"batteryLevel"];
  [super viewDidDisappear:animated];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  UIDevice *device = [UIDevice currentDevice];
  if ([object isEqual:device] && [keyPath isEqual:@"batteryLevel"]) {
    currentCharge.text = [NSString stringWithFormat:@"%.2f", device.batteryLevel];
  }
}
于 2009-11-03T00:21:30.297 に答える