i try to insert data in my NSMutableArray :
this is a part of my code:
newArray=[[NSMutableArray alloc]init];
fileArray = [[NSMutableArray alloc] initWithContentsOfFile: file];
[newArray insertObject:dict atIndex:[fileArray count] ];
it's crash with this error:
[__NSArrayM insertObject:atIndex:]: index 11 beyond bounds for empty array'
thanks for reading
NSMutalbeArray: insertObject:atIndex: method, the index value must not be greater than the count of elements in the array.
NSMutalbeArray: initWithCapacity: method, even though specify a size when create the array, the specified size is regarded as a “hint”; the actual size of the array is still 0.
The only method you can do to insertObject:atIndex, is to ensure to initialize all the elements before the index value.
for(int i = 0; i< index; i++) { [array addObject:[NSNull null]]; }
This should work:
newArray=[[NSMutableArray alloc]init];
fileArray = [[NSMutableArray alloc] initWithContentsOfFile: file];
[newArray addObject:dict];
First of all, as far as I know, when you call:
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity: 20]
It will create and return an NSMutableArray object with enough memory to initially hold a given number of objects. This is not a number of objects itself.
So, ( probably this isn't a good way ), you can fill your array with some null-objects like this:
for (NSInteger i = 0; i < 20; i++)
{
[array addObject:[NSNull null]];
}
And now you can use replaceObectAtIndex:WithObject: method for your purposes. Because I guess this is what you want ( insertObject:AtIndex: — means that you are going to insert an object at some index, but the rest part of the array (after that index) will "move", and there will be array.count+1 items now).
[array replaceObjectAtIndex:someIndex withObject:someObject];
You are trying to insert an object at an index that is greater then the array count.
This is because you are inserting the object into newArray, which has a count of 0 when you initialize it.
If you are really wanting to add the object to newArray, use index 0.
You can't add an object at a specific index if that index doesn't exist, and the way you're creating your array creates one with a length of 0.
You can either predefine the size of the array like this:
NSMutableArray *newArray = [[NSMutableArray alloc] initWithCapacity:20];
[newArray insertObject:object atIndex:index];
Or you can just insert objects from the beginning and let the array grow from 0, like this:
NSMutableArray *newArray = [[NSMutableArray alloc] init];
[newArray addObject:object];
Which will put it at index 0 if it's the first time you add an object, at index 1 the next time, etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.