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

为什么你会期望上面的代码不断更新?当视图出现时,您正在设置一次值。如果您希望它不断更新,您需要注册电池状态更新并在更改时重新绘制文本。

如果不查看您的程序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 回答