While-Loop works but not the if statement?
I have this while
loop in my code. The loop seems to work fine since I printed my i++
in the console. But for some reason 开发者_StackOverflow中文版it only checks my if
statement the first time around. I can only add one title into the NSMutableArray
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++;
}
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]]) {
//...
}
Yeah, you're comparing the pointers and not the values. Look at the documentation of NSString
, particular the isEqualToString:
method for comparing strings.
精彩评论