Reputation: 172
When I do the following my application crashes and I get an error (terminate called after throwing an instance of 'NSException') whenever i run the simulation:
for (...)
[Array1 replaceObjectAtIndex:i withObject: [NSString stringWithFormat:@" Trip %i",i+1]]
OK after writing the problem I have found that the error is "0 is beyond bounds for empty array".
Upvotes: 0
Views: 137
Reputation: 86651
You really really really need to post the type of exception and your code to give us a reasonable chance of solving your problem. However, I'm going to taker a shot at it anyway.
My guess is your code looks something like this:
Array1 = [[NSMutableArray alloc] initWithCapacity: someNumber];
for (i = 0 ; i < someNumber ; ++i)
{
[Array1 replaceObjectAtIndex:i withObject: [NSString stringWithFormat:@" Trip %i",i+1]];
}
All arrays start out with 0 objects in them even if you use -initWithCapacity:
. That method only provides a hint to the runtime that the array will grow to the specified size at some point. You need to use -addObject:
.
Edit
Yep, from your edit, I'm sure I am right. The array has started out empty and you are trying to replace the object at index 0 which isn't there yet.
The code above should be changed as follows:
array1 = [[NSMutableArray alloc] initWithCapacity: someNumber]; // fixed naming convention too :-)
for (i = 0 ; i < someNumber ; ++i)
{
[array1 addObject: [NSString stringWithFormat:@" Trip %i",i+1]];
}
-addObject:
adds the new objects to the end of the array.
If you want something that looks more like a C or Java array, you can prefill the array with NSNull
objects
array1 = [[NSMutableArray alloc] initWithCapacity: 6]; // fixed naming convention too :-)
for (i = 0 ; i < 6 ; ++i)
{
[array1 addObject: [NSNull null]];
}
// Now the following will work
[array1 replaceObjectAtIndex: 4 withObject: @"foo"];
Upvotes: 2
Reputation: 1239
Ok, here is a guess (I can't do better without more information):
You cannot change an object you are iterating over.
(Bad) Example:
for (NSObject *obj in Array1){
[Array1 replaceObjectAtIndex:i withObject: [NSString stringWithFormat:@" Trip %i",i+1]]
}
Upvotes: 1
Reputation: 31722
if you are using replaceObjectAtIndex
method with NSArray
array type object, there is possibility of getting exception (crashed).
Use NSMutableArray
for managing a modifiable array of objects.
Although replaceObjectAtIndex
can also be raised the following Exception for Object and Index
Index: Raises an NSRangeException
if index is beyond the end of the array.
Object: Raises an NSInvalidArgumentException
if Object you are passing is nil.
Upvotes: 1