On Aug 9, 2009, at 9:59 PM, Adam Gerson wrote:

I would like to insert objects out of order into an NSMutableArray.

I create the array with

NSMutableArray* cards = [[NSMutableArray alloc] initWithCapacity:5];

When I try to call

[cards insertObject:card atIndex:4];

I get the error:

*** -[NSCFArray insertObject:atIndex:]: index (4) beyond bounds (1)

Why doesn't this work?

Thanks,
Adam


Hi, Adam,

-insertObject:atIndex: requires the index to be within the existing bounds of the array. -initWithCapacity: doesn't fill the array--it only gives your array an internal "hint" as to what its size may be; it isn't filling it, as you may know, with anything. On modern systems, my understanding is that the benefits of using - initWithCapacity: over -init are generally negligible.

To reframe this: If you were to be inserting an object (card) at index 4 of your array (cards) after -initWithCapacity:, what would happen if you were to access the object at index 1, 2, or 3?

You'll need to insert objects sequentially and "build up" to the proper array size with the "card" object at the right position.

The documentation on the methods you referenced will likely be helpful on all these points.

Cheers,
        Andrew

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to