views:

423

answers:

2

I'm trying to figure out why this code doesn't work. I'm trying to search if a string contains "|P". If it does, I want to do something.

NSMutableArray *list = [pView getPOIList];
NSString *cellValue = [list objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
NSArray *chunks = [cellValue componentsSeparatedByString: @"|P"];
//NSLog([[chunks count] stringValue]);
if([&chunks[1] isEqualToString:@"|P"]) {
       //Do Something
}

This makes my app crash.

+3  A: 

NSArray *chunks is a NSArray, not a C array. You can use [chunks objectAtIndex:1] to find the object instead of &chunks[1].

To find if an sting contains an other string, you can use ([cellValue rangeOfString:@"IP"].length == 0). If the length of the range is 0, then the string doesn't exist in the original string. Reference

gcamp
Thanks. objectAtIndex was the problem. I also needed to split the string by just |, not |P.
Adam
If you are using rangeOfString it's better to look for .location = NS_NOT_FOUND (at lest I think it's a lot clearer what you are doing)
Kendall Helmstetter Gelner
+1  A: 

1. You don't index NSArrays by x[1]. You do it by the overly verbose [x objectAtIndex:1].

2. componentsSeparatedByString: will separate the string by |P, so if the string is:

.

  FOO|PURPLE|BAR|PIE|42|P|P2

The separated string will become

  ("FOO", "URPLE|BAR", "IE|42", "", "2")

you will not find an element in the resulting array containing the string |P. If you want to determine whether a substring exists, use rangeOfString:.

  NSRange substrRng = [cellValue rangeOfString:@"|P"];
  if (substrRng.location != NSNotFound) {
    ....
  }
KennyTM