简体   繁体   中英

ObjectAtIndex causes app to crash

When I do an NSLog of the contents of my NSMutableArray, it returns :

(
    hat,
    hat
)

So why is it that when I do an NSLog like so NSLog(@"%@", [pro.matches objectAtIndex:0]); it crashes with the error: *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'

So strange

This is where I fill it:

[self.matches removeAllObjects];

         NSArray *JSONarray = [[NSArray alloc] initWithArray:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]];
         int i;

         for (i=0; i<[JSONarray count]; i++) {
             //[self.matches addObject:[JSONarray objectAtIndex:i]];
             [self.matches addObject:@"hat"];
         }
         //NSLog(@"boys with bo%@", [[matches objectAtIndex:1] objectForKey:@"host"]);
         block();
         //JSON and add to matches.
     }
     }];
    block(); 

and this is where i call it:

[pro refreshMatchesWithCallback:^ 
    {
        //[self.tableView reloadData];
        NSLog(@"the count of a lifetime is %@", [pro.matches objectAtIndex:0]);
    }];

When you first log the contents it has nothing in due to the way completion blocks work, try this:

[pro refreshMatchesWithCallback:^ 
{
    //[self.tableView reloadData];
    if(pro.matches.count > 0) {
       NSLog(@"the count of a lifetime is %@", [pro.matches objectAtIndex:0]);
    }
}];

Hope this Helps!

Sam

always prefer to use this approach

for(Object* obj in arra)
{
...

}

this will enter in loop if the counter is greater than 0. no check needed

Cheerz :P

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM