Saturday, June 1, 2013

NSMutableArray initWithCapacity example in Objective C (iOS).


NSMutableArray initWithCapacity

Returns an array, initialized with enough memory to initially hold a given number of objects.

- (id)initWithCapacity:(NSUInteger)numItems

Parameters
numItems
The initial capacity of the new array.

Return Value
An array initialized with enough memory to hold numItems objects. The returned object might be different than the original receiver.

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

NSMutableArray initWithCapacity example.
- (id) initWithHeight: (int) height
{
    self = [super init];
    if (self)
    {
        self->myArr = [[NSMutableArray alloc] initWithCapacity:height];
    }
    return self;
}

Example of [NSMutableArray initWithCapacity].
@interface Foo : NSObject {
  NSMutableArray *objects;
}

@end

@implementation Foo

- (id) init {
  if (self = [super init]) {
    objects = [[NSMutableArray alloc] initWithCapacity:10]; // What
you are missing!
  }

  return self;
}

NSMutableArray initWithCapacity example.
i.e. I suggest using this:

[[NSMutableArray alloc] initWithCapacity: 16];

rather than this:

[[NSMutableArray arrayWithCapacity: 16] retain];

Both statements have the same net result but the first one avoids the overhead
of ever adding the object to the autorelease pool.


End of NSMutableArray initWithCapacity example article.