foho
foho

Reputation: 779

Array index beyond bounds

When I run the code below I get

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]

I understand that at some point in the loop not existed index of the array is reached. How to deal with that ?

 int main (int argc, const char * argv[])
    {

        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

        NSArray *t = [NSTimeZone knownTimeZoneNames];

        for(id x in t)
        {
            NSArray *tmpArray = [x componentsSeparatedByString:@"/"];
               NSLog(@"%@", [tmpArray objectAtIndex:1]);
        }
        [pool drain];
        return 0;
    }

Upvotes: 0

Views: 454

Answers (3)

Costique
Costique

Reputation: 23722

You should check the size of tmpArray first:

NSArray *tmpArray = [x componentsSeparatedByString:@"/"];
if ([tmpArray count] > 1)
    NSLog(@"%@", [tmpArray objectAtIndex:1]);

Upvotes: 1

AndersK
AndersK

Reputation: 36082

You may want to check the size of tmpArray before accessing index 1

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 385580

Not all time zones names contain a slash. For example, the UTC time zone name does not contain a slash. So tmpArray might only contain one string, at index 0.

Perhaps this will do what you want:

       NSLog(@"%@", [tmpArray lastObject]);

Upvotes: 4

Related Questions