Re: NSMutableArray initWithCapacity and insertObject:atIndex
Re: NSMutableArray initWithCapacity and insertObject:atIndex
- Subject: Re: NSMutableArray initWithCapacity and insertObject:atIndex
- From: "Henry McGilton (Boulevardier)" <email@hidden>
- Date: Sun, 9 Aug 2009 22:26:30 -0700
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];
initWithCapacity simply makes an array large enough to contain that
number
of elements. initWithCapacity is just a suggestion to the class
that you might
want to start with that number of elements.
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?
Based on the initialisation code, you have an array capable of holding
five elements
(with the potential for expanding as required), but that doesn't mean
there are five elements
in the array. After that initialisation, there are zero ( 0 )
elements in the array, and thus
any attempt to store beyond the last element will fail.
What you're apparently trying to do is have what's known as a 'sparse
array'. Take a look
at the NSIndexSet class to see if it helps you get where you want to
go . . ..
Another way to proceed (but for reasonably small arrays) would be to
allocate an array of
some size and initialise all its elements with instances of NSNull.
This idea would work only
in a limited universe of discourse --- clearly, if you wanted an
element at 0 (zero) and
another at (in Snow Leopard) 2 ^64, you're in trouble.
Poke around on the web for sparse array implementation techniques . . .
Cheers,
. . . . . . . . Henry
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden