I'm working on a battery indicator feature in my app, and I was wondering if there is a better way than what I am doing to check what image should be displayed when. I am currently using if
statements, but I was wondering if case statements would be a better option.
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UIDevice *device = [UIDevice currentDevice];
//Observer for the battery level
//Updates the percentage label and the battery icon
if (KEY_PATH_IF_THEN(@"batteryLevel")) {
LabelBatteryStatus.text = [NSString stringWithFormat:@"%.0f%%", device.batteryLevel * 100];
//shows battery image
if (kBatteryLevelBetween(100, 100)) {
batteryImage.image = [UIImage imageNamed:@"battery100fullycharged.png"];
} else if (kBatteryLevelBetween(99, 81)) {
batteryImage.image = [UIImage imageNamed:@"battery90.png"];
} else if (kBatteryLevelBetween(80, 65)) {
batteryImage.image = [UIImage imageNamed:@"battery75.png"];
} else if (kBatteryLevelBetween(64, 41)) {
batteryImage.image = [UIImage imageNamed:@"battery50.png"];
} else if (kBatteryLevelBetween(40, 35)) {
batteryImage.image = [UIImage imageNamed:@"battery30.png"];
} else if (kBatteryLevelBetween(34, 15)) {
batteryImage.image = [UIImage imageNamed:@"battery20.png"];
} else if (kBatteryLevelBetween(14, 0)) {
batteryImage.image = [UIImage imageNamed:@"battery10.png"];
}
}
}
kBatteryLevelBetween
:
#define kBatteryLevelBetween(higherNum,lowerNum) (device.batteryLevel *100 <= higherNum && device.batteryLevel *100 >= lowerNum)