Re: Calloc for Cocoa?
Re: Calloc for Cocoa?
- Subject: Re: Calloc for Cocoa?
- From: Marco Scheurer <email@hidden>
- Date: Mon, 30 Jun 2003 14:54:29 +0200
On Monday, June 30, 2003, at 06:11 AM, Tomas Zahradnicky wrote:
Hello,
I was used to use calloc(number_of_items, sizeof(item)) to create an
array of items. Is there some similar thing in Cocoa? The approach
like this seems me quite complex:
NSArray* a = [NSMutableArray arrayWithCapacity:number_of_items];
MyItem* item = NULL;
for(i=0; i<number_of_items; i++)
[a addObject:[[MyItem alloc] init];
Of course I can add a class method to my item class that does this,
but I'm asking if there's not already a way how to do that.
This is really comparing apples and bananas, but the "calloc
equivalent" of NSMutableArray would simply be:
NSMutableArray *a = [NSMutableArray arrayWithCapacity:number_of_items];
And you've got an empty array with number_of_items slots. Note:
1) This is "NSMutableArray *a" and not "NSArray *a"
2) This is not much complex, even simpler than calloc (number_of_items,
sizeof(item))
2) arrayWithCapacity is an optimization that you can use when the
number_of_items is known in advance, but is not necessary:
NSMutableArray capacity grows as needed. So NSMutableArray *a =
[NSMutableArray array] also works.
+(NSMutableArray*)arrayOfItems:(int)number
{
int i;
NSMutableArray* a = [NSMutableArray arrayWithCapacity:number];
for(i=0; i<number_of_items; i++)
[a addObject:[[[[self class] alloc] init] autorelease]];
return a;
}
Does it really make sense to fill an array with n identical copies of
some object? In that case this is beyond what calloc does. Or is it to
"initialize" the array? In that case this is unnecessary.
Marco Scheurer
Sen:te, Lausanne, Switzerland
http://www.sente.ch
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.