inforeqd
inforeqd

Reputation: 3249

NSMutableArray insertObject not adding into array

I'm trying to addobjects to a nsmutable array in lion, xcode 4.3 using ARC. the following is causing the program to crash with SIGABRT

 NSMutableArray *myArray = [NSMutableArray arrayWithCapacity:10];
 [myArray insertObject:@"Hello World" AtIndex:5]

how can i add custom objects to any index in the array?

Thanks in advance for your help.

Upvotes: 0

Views: 4365

Answers (4)

tia
tia

Reputation: 9698

If you want to use NSArray in the same manner of C fixed-size array, I suggest you fill the NSArray instance with as many [NSNull null] as you want for array size, e.g. 10 items in this case.

NSMutableArray *myArray = [NSMutableArray arrayWithCapacity:10];
for(int i = 0; i < 10; i++) {
    [myArray addObject:[NSNull null]];
}

And when you want to insert object, use replaceObjectAtIndex:withObject: instead. The size of the array won't change.

[myArray replaceObjectAtIndex:5 withObject:@"Hello World"];

You also need to check against [NSNull null] when accessing item.

id item = [myArray objectAtIndex:5];
if (item != [NSNull null]) {
    NSString* stringItem = item;
    // your code here
}

Upvotes: 3

ayoy
ayoy

Reputation: 3835

While your array capacity is 10, your array size right after creation is 0, so you can't insert element at index 5 because it's out of bounds.

Also, you can't insert nil into an array, but if you want to have an array with 10 nil elements as placeholders, you might use NSNull:

NSMutableArray *myArray = [NSMutableArray arrayWithCapacity:10];
for (int i = 0; i < 10; i++) {
    [myArray addObject:[NSNull null]];
}

// then this would work, but it inserts a new element, so your array size will be 11
// [myArray insertObject:@"Hello World" atIndex:5]
// to keep array size at 10 use this method:
[myArray replaceObjectAtIndex:5 withObject:@"Hello World"];

Upvotes: 4

Selvin
Selvin

Reputation: 12493

You are trying to insert object in an empty array, which wont work. Instead, try to add object. Try this...

NSMutableArray *myArray = [NSMutableArray arrayWithCapacity:10];
[myArray addObject:@"Hello World"];

Upvotes: 0

Mitul Nakum
Mitul Nakum

Reputation: 5574

If you have fix number of elements in array then use NSArray. Then you will able to set object for particular position. when you are using NSMutableArray, its size is 0. you have to have min 5 elements to insert at 5th position in NSMutableArray

Upvotes: 1

Related Questions