【问题标题】:Battery Level Will Not Update电池电量不会更新
【发布时间】:2009-11-03 00:08:24
【问题描述】:

我遇到了一个小问题。我是 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];
}

我最初得到的读数是正确的,但它没有更新。任何帮助将不胜感激!

非常感谢,

斯图尔特

【问题讨论】:

    标签: iphone objective-c timer battery


    【解决方案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];
      }
    }
    

    【讨论】:

    • 现在工作,非常感谢路易斯。就像我说的那样,我只是在学习,现在可以在将来正确地做到这一点。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多