• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Calloc for Cocoa?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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.

References: 
 >Calloc for Cocoa? (From: Tomas Zahradnicky <email@hidden>)

  • Prev by Date: Re: Calloc for Cocoa?
  • Next by Date: Don't know to achieve blue [any color] border when NSButtonCell is selected.Can anyone pls help?
  • Previous by thread: Calloc for Cocoa?
  • Next by thread: Re: Calloc for Cocoa?
  • Index(es):
    • Date
    • Thread