NSMutableArray insertObject
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index
Parameters of [NSMutableArray insertObject]
anObject
The object to add to the array's content. This value must not be nil.
Important: Raises an NSInvalidArgumentException if anObject is nil.
index
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]
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] 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 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 ];
}
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].
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];
}
}
{
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 example.
myArray = [[NSMutableArray alloc] init];
[myArray insertObject:[NSNumber numberWithFloat:myFloat] atIndex:myIndex];
[myArray insertObject:[NSNumber numberWithFloat:myFloat] atIndex:myIndex];