Showing posts with label Apple. Show all posts
Showing posts with label Apple. Show all posts

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++;
}
}

iPhone NSLog Basics

I'm most comfortable in Java. Ruby is favorite of mine as well. Lately, I've been diving into the iPhone platform. Objective-C is a beast compared to the Simula-based languages. My plan is to have lots of short notes on the frustrating little things that I'm learning.



CocoaDev has an awesome overview of printing to NSLog. This is absolutely the quickest and easiest way to debug on the iPhone. I was having a terrible time printing an integer to the log, being the Objective-C newbie that I am. NSLog takes printf syntax.



I was trying to parse the number of questions stored in a string and print that number to the log. I wrote a method in the same class that counted the number of questions in a string and returned an integer. Pitfalls:


  1. I forgot to send the method to the self object

  2. I didn't know the syntax for printf or NSLog


The correct solution looked just like this:

NSLog(@"you have %d questions", [self parseNumberOfQuestions]);