Search code examples
xcodeindexoutofboundsexceptionnsrangeexception

Xcode 4 NSRangeException Error after split string


I'm trying to split a string and separate it into variable but am getting the following error:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'

Code:

NSLog(@"%@", strResult);

    NSArray* LocInfo = [strResult componentsSeparatedByString: @"|"];
    NSString* Response1 = [LocInfo objectAtIndex: 0];
    NSString* Response2 = [LocInfo objectAtIndex: 1];
    NSString* Response3 = [LocInfo objectAtIndex: 2];

Any ideas? Thanks!


Solution

  • Your strResult is broken into LocInfo array that contains only two elements, and you tried to access third one.

    As your string already contains 1 / 2 or 3 NSStrings, therefore no need to again store then into NSString, you can directly use them by LocInfo[index].

    If you need to check how many strings are there simply use : [LocInfo count];