IOS应用程序崩溃::索引0超出空数组的边界

我有一个方法我将’id’传递到这里:

NSString *id = @"4bf58dd8d48988d181941735"; [self getNames:id]; 

这工作正常,但当我使用segue中传递的对象的’id’时:

 NSString *id = _selectedStore._id; [self getNames:id]; 

我收到错误:

 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array' 

这是怎么回事?

这是它得到错误的地方。 我的尝试(记住我是新手)是取一个Foursquare id的数组,得到名字,然后得到idUrl的id。 如果我删除所有创建photoUrl的代码(我已在代码中注明),它会运行而不会崩溃。

 - (void)getNames { NSMutableArray *final = [[NSMutableArray alloc] init]; for (SearchVenue *object in self.venues) { [Foursquare2 venueGetDetail:object._id callback:^(BOOL success, id result){ if (success) { NSDictionary *dic = result; NSArray *venue = [dic valueForKeyPath:@"response.venue"]; self.venueDetail = venue; NSMutableDictionary *newVen = [NSMutableDictionary dictionary]; [newVen setValue:[self.venueDetail valueForKey:@"name"] forKey:@"name"]; [final addObject:newVen]; [Foursquare2 venueGetPhotos:object._id limit:nil offset:nil callback:^(BOOL success, id result){ if (success) { NSDictionary *dic = result; NSArray *photos = [dic valueForKeyPath:@"response.photos"]; self.venuePhotos = photos; //works when removed from here... NSString *prefix = [[self.venuePhotos valueForKeyPath:@"items.prefix"] objectAtIndex:0]; NSString *size = @"100x100"; NSString *suffix = [[self.venuePhotos valueForKeyPath:@"items.suffix"] objectAtIndex:0]; NSArray *myStrings = [NSArray arrayWithObjects:prefix,size,suffix, nil]; NSString *photoUrl = [myStrings componentsJoinedByString:@"" ]; //...to here NSMutableDictionary *newVen1 = [NSMutableDictionary dictionary]; [newVen1 setValue:photoUrl forKey:@"photoUrl"]; for(int i = 0; i < [final count]; i++) { [[final objectAtIndex:i] addEntriesFromDictionary:newVen1]; } _arrayOfPlaces = final; NSLog(@"_arrayOfPlaces is %@",_arrayOfPlaces); [self.resultsVC reloadData]; } else { NSLog(@"%@",result); } }]; } else { NSLog(@"%@",result); } }]; } } 

你的问题可能在这里:

 NSString *prefix = [[self.venuePhotos valueForKeyPath:@"items.prefix"] objectAtIndex:0]; 

你应该做这个:

 if ([[self.venuePhotos valueForKeyPath:@"items.prefix"] count] > 0) { NSString *prefix = [[self.venuePhotos valueForKeyPath:@"items.prefix"] objectAtIndex:0] ... } else { // Do something for not having the prefix } 

如果你想要超安全,这总是好的,做到这一点

 if ([[self.venuePhotos valueForKeyPath:@"items.prefix"] isKindOfClass:[NSArray class]] && [[self.venuePhotos valueForKeyPath:@"items.prefix"] count] > 0) 

这也将确保该项目是一个数组。 如果1 [self.venuePhotos valueForKeyPath:@“items.prefix”] 1不是并且它没有响应计数,它将崩溃。

在使用索引访问数组之前,很少遵循的通用经验法则始终是检查边界。 无论您是通过下标还是objectAtIndex获取它。

  id object = __NSArrayI[i]; NSUInteger index = [__NSArrayI indexOfObject:object]; 

试试这个……先检查你的arrays数。