电池电量不会更新

Stu*_*umf 1 iphone battery timer objective-c

我有一个小问题.我是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];
}
Run Code Online (Sandbox Code Playgroud)

我最初正在阅读,但它没有更新.任何帮助将非常感激!

非常感谢,

斯图尔特

Lou*_*arg 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];
  }
}
Run Code Online (Sandbox Code Playgroud)