Saturday, June 1, 2013

NSMutableArray insertObject atIndex example in Objective C (iOS).

NSMutableArray insertObject atIndex

Inserts a given object into the array's contents at a given index.

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index

Parameters of [NSMutableArray insertObject atIndex]
The object to add to the array's content. This value must not be nil.
Important: Raises an NSInvalidArgumentException if anObject is nil.
The index in the array at which to insert anObject. This value must not be greater than the count of elements in the array.
Important: Raises an NSRangeException if index is greater than the number of elements in the array.

Discussion of [NSMutableArray insertObject atIndex]
If index is already occupied, the objects at index and beyond are shifted by adding 1 to their indices to make room.

Note that NSArray objects are not like C arrays. That is, even though you specify a size when you create an array, the specified size is regarded as a “hint”; the actual size of the array is still 0. This means that you cannot insert an object at an index greater than the current count of an array. [NSMutableArray insertObject atIndex] For example, if an array contains two objects, its size is 2, so you can add objects at indices 0, 1, or 2. Index 3 is illegal and out of bounds; if you try to add an object at index 3 (when the size of the array is 2), NSMutableArray raises an exception.

NSMutableArray insertObject atIndex example.
NSMutableArray * arrayToFill = [NSMutableArray array];
    for (int i = 0; i < 4; i++){
        NSDictionary * dictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"value1",  @"key1", @"value2", @"key2", nil];
        [arrayToFill insertObject: dictionary atIndex: i ];

Example of [NSMutableArray insertObject atIndex].
for(NSDictionary * dict in tempArray)
    if (dict) {

        NSString *btnName = [dict objectForKey:@"Name"];

        NSString *btnIndex = [dict objectForKey:@"btnIndex"];
        NSUInteger index = [btnIndex integerValue];

        [yourArray insertObject:btnName atIndex:index];
        [yourArray removeObjectAtIndex:index+1];

NSMutableArray insertObject atIndex example.
myArray = [[NSMutableArray alloc] init];
[myArray insertObject:[NSNumber numberWithFloat:myFloat] atIndex:myIndex];

End of NSMutableArray insertObject atIndex example article.