i try to change a bool value in dispatch_async when the applicationDidEnterBackground invoked. I can read the correct value when the method is invoked but when i try to use it in dispatch_asynch then i see that it is not the right value. Here how my code looks
Here NSLog(@"isWarningRepeatOn %d", isWarningRepeatOn) writes the right value but NSLog(@"ISWARNINGON %d", isWarningRepeatOn) writes the wrong one. What can be reason here ?
Code:
- (void)applicationDidEnterBackground:(UIApplication *)application {
__block BOOL isAlarmOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"alarmSituation"];
__block BOOL isWarningRepeatOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"warningRepeat"];
NSLog(@"isWarningRepeatOn %d", isWarningRepeatOn);
BOOL isVibrationOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"vibration"];
NSString *strSoundName = [[[NSUserDefaults standardUserDefaults] objectForKey:@"selectedSoundName"] lowercaseString];
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
__block UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
NSLog(@"ExpirationHandler about to expire...");
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self.operationQueue addOperationWithBlock:^{
while(TRUE) {
UIDevice *device = [UIDevice currentDevice];
[device setBatteryMonitoringEnabled:YES];
float batteryLevel = (float)[device batteryLevel] * 100;
self.theLevel = (int) ceil(batteryLevel);
NSInteger desiredBatteryLevel = [[NSUserDefaults standardUserDefaults] integerForKey:@"batteryLevel"];
if (isAlarmOn) {
if (isWarningRepeatOn) {
NSLog(@"ISWARNINGON %d", isWarningRepeatOn);
}
}
[[NSNotificationCenter defaultCenter] postNotificationName:@"UIDeviceBatteryLevelDidChangeNotification" object:self userInfo:nil];
[NSThread sleepForTimeInterval:10]; //wait for 1 sec
}
}];
});
}
}
Here NSLog(@"isWarningRepeatOn %d", isWarningRepeatOn) writes the right value but NSLog(@"ISWARNINGON %d", isWarningRepeatOn) writes the wrong one. What can be reason here ?