电池电量不会更新

问题描述:

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

我正确地获取最初的阅读,但它没有更新。任何帮助将非常感激!

非常感谢,

斯图尔特

为什么你会想到上面的代码,以持续更新?出现视图时,您正在设置该值一次。如果您希望持续更新,则需要注册电池状态更新,并在文本更改时重新绘制文本。

没有看到您的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]; 
    } 
} 
+0

现在工作非常非常感谢你路易斯。就像我说过的,我只是在学习,现在可以在将来正确地做到这一点。再次感谢! – Stumf 2009-11-03 00:49:00