DuskFall
DuskFall

Reputation: 422

NSMutableArray always empty

NSMutableArray *experienceValues;
experienceValues = [NSMutableArray alloc] initWithObjects:0,83,174,276,nil];

NSLog(@"%@", [experienceValues objectAtIndex:3]);

Why does this always throw -[__NSArrayM objectAtIndex:]: index 3 beyond bounds for empty array when it is clearly allocated and initialised in the line just before?

Upvotes: 2

Views: 127

Answers (6)

Master Stroke
Master Stroke

Reputation: 5128

You're trying to add integer value to NSArray.

NSMutableArray *experienceValues = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithInteger:42],nil];

then convert it back to integer like,

NSLog(@"%@", [experienceValues objectAtIndex:0]);

Upvotes: 1

Andrea
Andrea

Reputation: 26385

The NSMutableArray class as most of the collection classes in cocoa, accepts only objects. So if you want to put numbers, you can't put primitive type, but only instances of NSNumber class, thus:

[[NSMutableArray alloc] initWithObjects:[NSNumber numberWithInt:0]...etc

Or with literals:

[[NSMutableArray alloc] initWithObjects:@0,@83,@174,@276.. etc

Upvotes: 3

The iOSDev
The iOSDev

Reputation: 5267

Try this

NSMutableArray *experienceValues = [[NSMutableArray alloc] initWithObjects:@0,@83,@174,@276,......., nil];

NSLog(@"%d", [experienceValues objectAtIndex:3]);

As initWithObjects: accepts only object you need to put only objects in it

Upvotes: 1

David Rönnqvist
David Rönnqvist

Reputation: 56625

The array is empty because the arguments are nil terminated and 0 is interpreted as nil.

The array should only contain objects (as opposed to primitives like ints). In you case you should create NSNumbers for all the numbers. You can do that with the number literal syntax @2.0.

Upvotes: 2

trojanfoe
trojanfoe

Reputation: 122381

Objective-C collection classes can only store objects; not primitives like int.

You need to wrap them in NSNumber objects.

If these are literal values then the answer provided by @Kirsteins demonstrates the syntax.

Upvotes: 1

Kirsteins
Kirsteins

Reputation: 27335

You need to wrap integer values like @0, @83, @174, ..., as primitive integers are no objects.

Upvotes: 3

Related Questions