Adam
Adam

Reputation: 255

NSString Value of NSArray Object

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.

Upvotes: 2

Views: 1539

Answers (2)

kennytm
kennytm

Reputation: 523304

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) {
    ....
  }

Upvotes: 2

gcamp
gcamp

Reputation: 14662

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

Upvotes: 4

Related Questions