简体   繁体   中英

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??

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

请检查您的阵列计数在位置2处没有得到项目

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM