replaceObjectAtIndex error?
The following code:
NSMutableArray *kkk = [NSMutableArray arrayWithCapacity: 20];
[kkk replaceObjectAtIndex:10 withObject: @"cat"];
yields this
开发者_高级运维Terminating app due to uncaught exception 'NSRangeException', reason: ' -
[NSMutableArray replaceObjectAtIndex:withObject:]: index 10 beyond bounds for empty array' Call stack at first throw:
arrayWithCapacity:
allocates the required memory but it doesn't fill the array with objects. nil
isn't a valid object to fill the array. So if you need an array with empty objects, you will have to do something like this,
int size = 20;
NSMutableArray *kkk = [NSMutableArray arrayWithCapacity:size];
for ( int i = 0; i < size; i++ ) {
[kkk addObject:[NSNull null]];
}
Now you can safely replace objects,
[kkk replaceObjectAtIndex:10 withObject: @"cat"];
Getting an array with that capacity does not fill it with elements; it's still an empty array when you try to replace the object at index 10. If you provide more detail as to the context in which this is happening, I can try to suggest a way around the problem.
EDIT: if you must have an array with objects right away, try this:
NSMutableArray *kkk = [NSMutableArray arraywithObjects: @"", @"", @"", @"", nil];
except with 20 @""
's instead of four. Then you get an array of 20 strings. Be sure to put retain
on the end of it if you're using it outside the immediate scope, though, since arrayWithObjects
returns an autoreleased array.
精彩评论