Robert Myers
Robert Myers

Reputation: 51

[__NSArrayM objectAtIndex:]: index 2 beyond bounds for empty array

I get the error:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSA

Here is my code:

static NSArray * clone(NSArray * a, NSUInteger b)
{
    // return a.slice(b);
    return [a subarrayWithRange:NSMakeRange(b, a.count - b)];
}
// swap: function(a, b) {
static NSArray * swap(NSArray *a, NSUInteger b)
{
    NSMutableArray * array = [NSMutableArray arrayWithArray:a];

// var t1, t2;
id t1, t2;

// t1 = a[0];
t1 = array.firstObject;

// t2 = a[b % a.length];
t2 = array[b % a.count];

// a[0] = t2;
array[1] = t2;

// a[b] = t1;
array[b] = t1;

// return a;
return array.copy;
}

I'm confused on why it is giving me the error. This is just a snippet of the code, This comes from a modified version of HCYoutubeParser.

Upvotes: 1

Views: 1802

Answers (1)

user1453351
user1453351

Reputation:

Because simply if you debug your application, you'll find that in this line

array[1] = t2;

The variable array doesn't have 2 items to access the item #1, it contains either 0 or 1 item, you should do a check like this

if (array.count >= 2) {
    array[1] = t2;
}

Upvotes: 3

Related Questions