daleijn
daleijn

Reputation: 738

Check NSMutableArray element is exist

I get the data from the network. In ViewDidLoad method I init and retain my array:

arrBannersIMG = [[NSMutableArray alloc]init];
 [arrBannersIMG retain];

In CellForRowAtIndexPath I need to check if arrBannersImg[indexPath.row] is exist, if YES - set cell.image from this array, if not - init UIImage by data from Internet, and add this image to arrBannersIMG. I tried this:

 if (_arrayOfImages[indexPath.row] == [NSNull null]) {
       //
}

But I have error on this line:

Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'

I can check array like this:

if (!array || !array.count){
  ...
}

But I need to check current element, not all array. How can I do this?

Upvotes: 0

Views: 387

Answers (3)

anshul-systematix
anshul-systematix

Reputation: 416

Firstly I would suggest you that as per your condition you should work with arrays out of CellForRowAtIndexPath method.

This is because may be your array is already empty and you are trying to compare it with indexpath.row that is not exist. Thats why its crashed.

Firstly you should check that _arrayOfImages has any count or not.

_arrayOfImages=arrBannersIMG;

if([_arrayOfImages count]>0)
{ 
 NSData *imgData = UIImageJPEGRepresentation([_arrayOfImages indexPath.row], 0);
UIImage  *img = [UIImage imageWithData:[_arrayOfImages indexPath.row];
}
else
{
 //init UIImage by data from Internet
arrBannersIMG= //Insert your image object in array
}

I don't know your whole scenario , but this kind of array implementation will save us by crash if we access it out of delegate methods like CellForRowAtIndexPath.

Hope it helps. please check and let me know if we have to go with another solution.

Upvotes: 0

Nicolas Bonnet
Nicolas Bonnet

Reputation: 1274

I'm not sure why you want look elements inside a empty array but to solve this error, try that :

if(array.count > indexPath.row) {
    if (_arrayOfImages[indexPath.row] == [NSNull null]) {
        // ...
    }
}

Hope that will help.

Upvotes: 0

Wain
Wain

Reputation: 119031

You should probably change your approach and leverage some open source code. You don't want to be using a sparsely populated array really (fast scrolling could cause you issues). You also want to be sure to download images in the background.

Look at using SDWebImage and just storing all of the image URLs in your array. Now, when you need to display the image just pass the URL to SDWebImage and it will load from the cache / internet as required for you.

Upvotes: 1

Related Questions