0
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIDevice *device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];
}

- (void)batteryChanged:(NSNotification *)notification
{
    UIDevice *device = [UIDevice currentDevice];
    NSLog(@"State: %i Charge: %f", device.batteryState, device.batteryLevel);
    batteryLabel.text = [NSString stringWithFormat:@"State: %i Charge: %f", device.batteryState, device.batteryLevel];
}

UILabel 永远不会更新。电源的事件永远不会被触发。

难道我做错了什么?

我计划只支持 iOS 5.x 和 6

4

2 回答 2

0

如果您让通知中心正常工作,但 UILabel 没有更新,难道不是因为收到通知时应用程序处于后台吗?

我会尝试以下方法:

  1. 查看 uilabel 是否正确连接到情节提要
  2. 应用从睡眠中唤醒后更新 uilabel
于 2012-07-06T10:29:26.080 回答
0
IBOutlet UILabel *currentBatteryStatusLabel;

我将上面的代码更改为以下代码,一切都开始工作了。

__weak IBOutlet UILabel *currentBatteryStatusLabel;

我不知道为什么它会产生如此大的不同

于 2012-07-06T12:48:45.803 回答