2009-11-03 6 views
1

작은 문제가 있습니다. 나는 초보자 인 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]; 
} 

처음에는 올바르게 읽었지만 업데이트되지는 않았다. 어떤 도움을 많이 주시면 감사하겠습니다!

많은 감사,

스튜어트는

답변

6

왜 지속적으로 업데이트하려면 위의 코드를 기대? 뷰가 표시되면 값을 한 번 설정합니다. 지속적으로 업데이트하려면 배터리 상태 업데이트를 등록하고 변경된 텍스트를 다시 그려야합니다.

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

관련 문제