David Ben Ari
David Ben Ari

Reputation: 2299

weird index 2 beyond bounds for empty array error

I can't seem to find what's wrong. here is my code:

NSMutableArray *sortedActivities = [NSMutableArray arrayWithCapacity:self.trainingSession.activities.count];
for (ManagedActivity *activity in self.trainingSession.activities)
    [sortedActivities insertObject:activity atIndex:[activity.activityIndex unsignedIntegerValue]];

as you can see i want to sort the set of activities (which is a relation in trainingSession) by the a property named activityIndex inside the activity. the indexes of the activities are always from 0 on, that means that none of the indexes exceeds trainSession.activities.count-1.

i do the sorting by allocating a NSMutableArray with the appropriate capacity, and then iterate over the activities (once) and insert them to the right index. for some reason that i don't know i get this error:

Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM insertObject:atIndex:]: index 2 beyond bounds for empty array'

i tried retaining the array, it didn't matter (and shouldn't matter).

the indexes are correct, the count is correct, what is wrong??

Upvotes: 2

Views: 2187

Answers (2)

user3306145
user3306145

Reputation: 76

Please check your array count its not getting item at position 2

Upvotes: 0

fzwo
fzwo

Reputation: 9902

The capacity in arrayWithCapacity: is just a hint for optimization. The array still has a count of 0.

Upvotes: 6

Related Questions