上記のコードが継続的に更新されると期待するのはなぜですか?ビューが表示されたら、値を1回設定します。継続的に更新する場合は、バッテリーステータスの更新を登録し、変更されたときにテキストを再描画する必要があります。
あなたbatteryLevel
とupdateBatteryLevel:
ルーチンのコードを見なければ、あなたが何をしているのか、なぜそれらがうまくいかないのかを実際に知る方法はありません。そうは言っても、私はこれにタイマーイベントを使用しないでしょう、それはかなり非効率的です。代わりに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];
}
}