Reputation: 1878
I am using key/value method to save integer to NSUserDefaults. I have like 30 different cases in a switch and case where each case saves an integer value to a specific key. And I have created one method for each integer that is being saved. Heres some code to explain:
-(void) saveInteger1:(NSInteger)int1 {
[[NSUserDefaults standardUserDefaults] setInteger:int1 forKey:@"Integer1"];
}
-(void) saveInteger2:(NSInteger)int2 {
[[NSUserDefaults standardUserDefaults] setInteger:int2 forKey:@"Integer2"];
}
-(void) saveInteger3:(NSInteger)int3 {
[[NSUserDefaults standardUserDefaults] setInteger:int3 forKey:@"Integer3"];
}
//And I got from 1-30 of these methods
switch (newInteger) {
case 1:
[self saveInteger1:newInteger];
break;
case 2:
[self saveInteger2:newInteger];
break;
case 3:
[self saveInteger3:newInteger];
break;
//And from 1-30 cases
}
What is a more effectively way to do this so it won't be so many lines of code?
Upvotes: 0
Views: 84
Reputation: 318824
Are all of the keys of the form IntegerX
? If so then do:
- (void)saveInteger:(NSInteger)value {
NSString *key = [NSString stringWithFormat:@"Integer%d", value];
[[NSUserDefaults standardUserDefaults] setInteger:value forKey:key];
}
[self saveInteger:newInteger];
No switch
statement is required.
Upvotes: 3