电源断开时,iOS UILabel不会改变

时间:2012-07-05 16:57:33

标签: ios5 notifications uilabel nsnotificationcenter uidevice

- (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

2 个答案:

答案 0 :(得分:0)

如果您的通知中心正常运行,但UILabel没有更新,是不是因为收到通知时应用程序处于后台?

我会尝试以下方法:

  1. 查看uilabel是否正确连接到故事板
  2. 应用程序从睡眠状态唤醒后更新uilabel

答案 1 :(得分:0)

IBOutlet UILabel *currentBatteryStatusLabel;

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

__weak IBOutlet UILabel *currentBatteryStatusLabel;

我不确定为什么它会产生如此大的差异