caribbean
caribbean

Reputation: 748

Declare array with no definite size in Objective-C

I need an array of strings that contains nothing at initial declaration because I will use it as storage of strings that I will get from the users. I will do this through looping. Anybody knows how to declare an array with no definite size initially using NSArray? Thanks!

Upvotes: 0

Views: 936

Answers (4)

occulus
occulus

Reputation: 17014

I assume you're meaning NSMutableArray.

NSMutableArray can expand to hold any amount of objects (given memory limitations). Just make it the usual way: [[NSMutableArray alloc] init] and then add objects.

Every NSMutableArray has a initial capacity. If you exceed this amount of objects, some book-keeping happens behind the scenes to adjust for a larger capacity, but it's not something you need to do anything about.

If you know that an NSMutableArray is going to hold X objects, and no more, you can specify that the array has that capacity:

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:X];

This means that no behind the scenes resizing of the array will happen at a later time. It's a performance/efficiency improvement, but you code will still work even if you don't do this.

Upvotes: 5

Krunal
Krunal

Reputation: 6490

NSMutableArray with no definite size,

NSMutableArray *array=[[NSMutableArray alloc] init];

Upvotes: 4

Roshan
Roshan

Reputation: 1937

  1. [[NSArray alloc] init] and use array = [array arrayByAddingObject:string]

  2. [[NSMutableArray alloc] init] and use [array addObject:string]

Upvotes: 2

trojanfoe
trojanfoe

Reputation: 122391

Simply use NSMutableArray which allows elements to be added and removed (i.e. mutable):

NSMutableArray *array = [[NSMutableArray alloc] init];

or, using the new Objective-C literals syntax:

NSMutableArray *array = @[];

Upvotes: 3

Related Questions