views:

57

answers:

2

I have this while loop in xcode. The loop seems to work fine since I printed my i++ in console. But for some reason it only checks my IF statement the first time around. I can only add one title into the MutableArray called sectionZeroTitleArray. I have many arrays in this loop so it might get confusing. I will try my best to explain.

Here is what I am trying to do: Loop through the length of an array(topicArray). If the array's(topicArray)is the same as this other array's(anotherArray) first object then add an object that has the same index(titleArray) as topicArray to a new MutableArray(sectionZeroTitleArray).

I'm sure I did something stupid, maybe someone that hasn't stared at this all day can fix me up? Please and thank you.

while (i < (topicArray.count)) {
  if ([topicArray objectAtIndex:i] == [anotherArray objectAtIndex:0]) {
   [sectionZeroTitleArray addObject:[titleArray objectAtIndex:i]];
  }
  NSLog(@"sectionZeroLoopCount: %d", i);
  i++;
 }
+5  A: 

You are checking for pointer equality when you use ==. Are you sure you want to do this? What is the type that you're expecting? If it's a NSString, use isEqualToString:, otherwise use NSObject's isEqual: method:

If the expected type is an NSString:

if([[topicArray objectAtIndex:i] isEqualToString:[anotherArray objectAtIndex:0]]) {
   //...
}

Otherwise, you should probably do this:

if([[topicArray objectAtIndex:i] isEqual:[anotherArray objectAtIndex:0]]) {
   //...
}
Jacob Relkin
+1  A: 

Yeah, you're comparing the pointers and not the values. Look at the documentation of NSString, particular the isEqualToString: method for comparing strings.

jer