Reputation: 21
I want to create an NSArray populating of NSDictionary and print in console the first value of every array's element.
I receive the following error:
Terminating app due to uncaught exception 'NSRangeException', reason:' -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]' * First throw call stack: (0x30d77e83 0x3b0d46c7 0x30cadd95 0xb93b3 0xb8e03 0x3175ccdd 0x30d42e7f 0x30d42a9b 0x30d40e23 0x30cab471 0x30cab253 0x359e52eb 0x33560845 0xb8abd 0x3b5cdab7)
libc++abi.dylib: terminating with uncaught exception of type NSException
-(void) listOp {
NSDictionary *dictionary;
NSMutableArray *array;
NSNumber *refNum;
int numOp = [_refNum intValue];
self.array = [NSMutableArray arrayWithObjects: self.dictionary, nil];
for ( int i = 0; i < numOp; i++){
[self.array insertObject:self.dictionary atIndex:i];
NSDictionary* vardebug = nil;
vardebug = [self.array objectAtIndex:numOp];
NSString *valuekey = [self.dictionary valueForKey: @"key"];
NSLog(@"Valuekey is: %@", valuekey);
}
}
Don't understand what is going wrong.
Upvotes: 0
Views: 5698
Reputation: 1964
Replace vardebug = [self.array objectAtIndex:numOp];
by vardebug = [self.array objectAtIndex:i];
should avoid the crash.
Upvotes: 0
Reputation: 25459
Your code is a little bit messy. You declare:
NSDictionary *dictionary;
NSMutableArray *array;
And after that you call
self.dictionary...
self.array...
You use self if you have property, for example;
@property(nonatomic, strong) NSDictionary *dictionary;
so basically if you want to access your:
NSDictionary *dictionary;
NSMutableArray *array;
you should call, for example:
array = [NSMutableArray arrayWithObjects: dictionary, nil];
Without self. But maybe you have both ivar shown in this example and property and you do it by purpose. I just want to say that if you do it by purpose you should use different names just to make your code more clear.
The error you have happened in line:
vardebug = [self.array objectAtIndex:numOp];
In your first loop iteration you have already one item in the array (added during allocation) and you insert another one so you array contains 2 object but you numOp is equal 2 which refer to 3rd object in the array (array are zero base) so the call is beyond bounds. I guess you want to change it to:
vardebug = [self.array objectAtIndex:i];
Hope this help
Upvotes: 0