Reputation: 481
I'm trying to access the elements of an array and change them such as I have an array with numbers and variables x, I have to go through the array and replace the variables x with values. I tried this but I get an error at the for statement which is Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 .. 2]'
if( [stack containsObject:@"X"] )
{
int x;
for(x=0; [stack objectAtIndex:x] ;x++)
{
[stack replaceObjectAtIndex:x withObject:[variableValues objectForKey:@"X"]];
}
Upvotes: 0
Views: 717
Reputation: 15588
What is the error you are getting? Could be a couple of things looking at your code. if the array is length zero, then accessing object at index 0 will throw an error. Also, the array needs to be mutable for the replacing to work.
-- update Also, if your objectForKey returns nil, in the replacement method, trying to replace nil will also throw an error. See updated code below:
if( [stack containsObject:@"X"] )
{
assert([stack isKindOfClass:[NSMutableArray class]] );
NSUInteger count = [stack count];
for(NSUInteger x = 0; x < count ;x++)
{
id value = [variableValues objectForKey:@"X"];
if ( value != nil )
{
[stack replaceObjectAtIndex:x withObject:value];
}
}
}
Upvotes: 1