Saturday, June 1, 2013

NSMutableArray arrayWithCapacity example in Objective C (iOS).


NSMutableArray arrayWithCapacity

Creates and returns an NSMutableArray object with enough allocated memory to initially hold a given number of objects.

+ (id)arrayWithCapacity:(NSUInteger)numItems

Parameters
numItems
The initial capacity of the new array.

Return Value
A new NSMutableArray object with enough allocated memory to hold numItems objects.

Discussion of [NSMutableArray arrayWithCapacity]
Mutable arrays expand as needed; numItems simply establishes the object’s initial capacity.

NSMutableArray arrayWithCapacity example.
-(NSMutableArray *)FunctionB:(int)count {

 NSMutableArray *b = [NSMutableArray arrayWithCapacity:count];

 for (int i=0;i   [b addObject:[NSNumber numberWithInt:0] ]; 
 }

 return b;  //  or [b autorelease] ?
}

Example of [NSMutableArray arrayWithCapacity].
There are two ways to create objects in Cocoa:

NSMutableArray* array1 = [[NSMutableArray alloc] initWithCapacity:10];
NSMutableArray* array2 = [NSMutableArray arrayWithCapacity:10];
array1 was created using alloc+init, therefore you own it. It will stick around until you release it.

array2 was not created using alloc+init, therefore you do not own it. You're not responsible for releasing it, but it will go away on its own. You must retain array2 if you want it to stick around.

NSMutableArray arrayWithCapacity example.
This is how things implemented behind the scene:

+(NSMutableArray*) new
{
    return [[NSMutableArray alloc] init];
}
and

+(NSMutableArray*) arrayWithCapacity:(NSNumber)capacity
{
    return [[NSMutableArray alloc] initWithCapacity:capacity] **autorelease**];
}
In first case the array is allocated only and you're responsible for de-allocating it. In contrary the arrayWithCapacity has autoreleased for you and won't cause leak even you forget to deallocate.

End of NSMutableArray arrayWithCapacity example article.