I'm currently trying to make the code of an app I'm developing a bit more efficient and easier to read. Basically what this does is after the user taps with two fingers (gesture) it retrieves a previously saved array from NSUserDefaults
of player names, and fills in the 6 text boxes (tagged 6-11) on a table view with these names. If there isn't an existing array it'll use a default set of names.
I'm trying to reduce the length of a long for
/if
statement. Any ideas for simplifying this code would be appreciated.
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
NSMutableArray *names = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"nameArray"]];
for (int i = 0; i <= 5; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
UITableViewCell *cell = [playerTable cellForRowAtIndexPath:indexPath];
for (UIView *view in cell.contentView.subviews) {
if ([view isKindOfClass:[UITextField class]]) {
UITextField *txtField = (UITextField *)view;
if (txtField.tag == 6) {
if([[NSUserDefaults standardUserDefaults] boolForKey:@"customNames"]) {
txtField.text = [names objectAtIndex:0]; }
else {
txtField.text = @"Peter";
}
}
if (txtField.tag == 7) {
if([[NSUserDefaults standardUserDefaults] boolForKey:@"customNames"]) {
txtField.text = [names objectAtIndex:1]; }
else {
txtField.text = @"Julia";
}
}
if (txtField.tag == 8) {
if([[NSUserDefaults standardUserDefaults] boolForKey:@"customNames"]) {
txtField.text = [names objectAtIndex:2]; }
else {
txtField.text = @"Durgan";
}
}
if (txtField.tag == 9) {
if([[NSUserDefaults standardUserDefaults] boolForKey:@"customNames"]) {
txtField.text = [names objectAtIndex:3]; }
else {
txtField.text = @"Bob";
}
}
if (txtField.tag == 10) {
if([[NSUserDefaults standardUserDefaults] boolForKey:@"customNames"]) {
txtField.text = [names objectAtIndex:4]; }
else {
txtField.text = @"Iseland";
}
}
if (txtField.tag == 11) {
if([[NSUserDefaults standardUserDefaults] boolForKey:@"customNames"]) {
txtField.text = [names objectAtIndex:5]; }
else {
txtField.text = @"Player";
}
}
}
}
}
[self saveNames];
}
Edit: I've received an answer elsewhere and it greatly reduces the length as well as making it more readable:
NSArray *defaultNames = @[@"Peter", @"Julia",...];
int offsetIndex = 6;
BOOl needCustomNames = [[NSUserDefaults standardUserDefaults] boolForKey:@"customNames"];
for (UIView *view in cell.contentView.subviews)
{
if ([view isKindOfClass:[UITextField class]])
{
UITextField *txtField = (UITextField *)view;
int index = [txtField tag]-offsetIndex;
if (txtField.tag >= 6 && txtField.tag <= 11)
{
if (needCustomNames)
txtField.text = [names objectAtIndex:index];
else
txtField.text = [defaultNames objectAtIndex:index];
}
}
}
if
structure of the code. That point is pretty well hidden now. – GraniteRobert Jul 10 '14 at 13:00