Wednesday, April 7, 2010

Objective-C For-Each Loops and String Comparisons

I have a NSArray of NSString objects I want to loop through. I want to compare every string to another string; if they're equal I want to increment a counter, and if not I want to do nothing.



Thanks to pointers and the message-passing style of Objective-C, I ran into some trouble.


  1. Not addressing items by pointers -- that * is critical!

  2. Forgetting the oft-used square brackets

  3. Not knowing how to do a string comparison -- thanks, StackOverflow!



In Java, the loop portion would look like this:


for (String s : myArray) {
if (s.equals("myCheck"))
count++;
}


In Objective-C 2.0, it looks like this:

for (NSString* s in myArray) {
if ([s isEqualToString:@"myCheck"]) {
count++;
}
}

No comments:

Post a Comment