简体   繁体   中英

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?

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.

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.

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.

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