iOS error: [__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]

末鹿安然 提交于 2019-11-29 12:10:59

Somewhere you are likely accessing _videos prior to initializing it. Most likely you'd doing it after init, but prior to loading the view. The fix for this kind of problem is to use accessors exclusively, and to lazy-initialize self.videos. This is one of many reasons never to access your ivars directly except in init and dealloc.

@interface ...
@property (nonatomic, readonly, strong) NSMutableArray *videos;
@end

@implementation ...
{
  NSMutableArray *_videos; // Can't auto-synthesize. We override the only accessor.
}

- (NSMutableArray *)videos {
   if (! _videos) {
     _videos = [NSMutableArray new];
   }
   return _videos;
}

Now all references to self.videos will be initialized no matter when they happen.

You can also initialize videos correctly in init, which takes a little less code:

@interface ...
@property (nonatomic, readonly, strong) NSMutableArray *videos;
@end

@implementation ...

- (id)init {
   self = [super init];
   if (self) {
     _videos = [NSMutableArray new];
   }
   return self;
}

I had the same error signature -[__NSArrayI objectAtIndex:]: index 4 beyond bounds [0 .. 1]' when attempting to present a modal Storyboard, table view with two (updated from five) static table cell sections. This error didn't come up until I removed three table cell sections I no longer needed in the view. After checking all my objectAtIndex references preceding the modal presentation at length for two days, I decided to look at the UITableViewController subclass code itself. I found this:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 5;
}

Then the lightbulb went off. The index 4 being referred to related to my table view number of sections and the bound of [0 .. 1] referred to my current two table cell sections. Updating the return value to match the number of current table cell sections in the Storyboard table view resolved the issue.

Narasimha Nallamsetty

I have passed dummy image name for images array like this,

arrImages = [NSArray arrayWithObjects:[UIImage imageNamed:@"some.png"]

The above line caused me error. So I changed @"some.png" with existed image like @"category.png".

This is worked for me. Make sure you are passing correct image name from your bundle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!