Search code examples
objective-cnsstringnsarray

Obj-C - Can't access values in NSArray?


I have a textView that displays the string: 255,34,7,4

I'm trying to use the following code to pull the string from my textView, and separate each number into an array:

        NSArray *array = [self.textview.text componentsSeparatedByString:@","];
        NSString *comp1 = array[0];
        NSString *comp2 = array[1];
        NSString *comp3 = array[2];

This works, and the following is returned to my array:

> 2020-07-11 15:21:58.110560-0700[10116:2311809] In the array you will
> find (
>     255,
>     34,
>     7,
>     4 )

However I'm unable to access the second and third values with array[1] and array[2]? My app crashes with the following error:

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

Why is this happening?


Solution

  • because the moment you try to access the expected objects do not exist. It is much safer to ask for the amount of indexes available in an array before accessing indexes that may not exist at runtime.

    NSArray *splitarray = [self.textview.text componentsSeparatedByString:@","];
    
    NSLog(@"amount of indexes %lu", splitarray.count);
    
    for (NSString *idxObject in splitarray) {
        NSLog(@"content @%",idxObject);
    }
    

    or

    for (NSUInteger i=0; i<splitarray.count; i++) {
        NSLog(@"content @%",splitarray[i]);
    }
    

    NSArray and a lot of other indexed data types do not check if an index exists to speed up accessing and they are also not constructed to return nil in case the index does not exist.