0

I had seen a code like this

if ([[dict objectForKey:@"name"] rangeOfString:@“AB”].location != NSNotFound ||
    [[dict objectForKey:@"name"] rangeOfString:@“CD”].location != NSNotFound ||
    [[dict objectForKey:@"name"] rangeOfString:@“EF”].location != NSNotFound ||
    [[dict objectForKey:@"name"] rangeOfString:@“GH”].location != NSNotFound ||
    [[dict objectForKey:@"name"] rangeOfString:@“IJ”].location != NSNotFound ||){
    // do something
   }

Which I changed to:

NSArray *myArray = [NSArray arrayWithObjects:@“AB”,
                @"CD", @"EF", @"GH", @"IJ", nil];

for (id object in myArray) {
    if ([[dict objectForKey:@"name”] rangeOfString: id].location != NSNotFound){
        // do something
        break;
    }
}

I understand readability is better after changing the code. Does it have any other advantages?

3
  • 1
    nothing that im aware of, but just being anal here, you should make your for loop like for(String <#stringName#> in myArray) rather, and if you want you can change [dict objectForKey:@"name”] to just dict[@"name"] but thats debatable whether thats more readable (less explicit, but less clutter which i prefer) Commented Jan 12, 2015 at 5:23
  • Why are you using the C tag? Commented Jan 12, 2015 at 5:28
  • I agree the code is written in Objective-c but I felt the use-case is applicable for c also. Will remove the tag. Commented Jan 12, 2015 at 5:34

1 Answer 1

2

I don't see any substantial difference. You could further improve readability and terseness by pulling the dictionary access out of the loop.

// probably done for you by the compiler, but still prettier to look at...
NSString *name = dict[@"name"];

for (id object in myArray) {
    if ([name rangeOfString:id].location != NSNotFound){
        // do something
        break;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Agree. Minor note: The compiler can't do the optimization as the dict lookup is invisible to it and may have side effects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.