简体   繁体   中英

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM