Search code examples
objective-cuiimageviewuiimagensmutablearrayafnetworking

Add UIImage to NSMutableArray at Specified Index via AFNetworking


I'm fetching images from web service using the code below in my cellForRowAtIndexPath:

[cell.posterImageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[postersURLArray objectAtIndex:indexPath.row]]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
     {
         if (request)
         {
             [UIView transitionWithView:cell.posterImageView
                               duration:1.0f
                                options:UIViewAnimationOptionTransitionCurlUp
                             animations:^{[cell.posterImageView setImage:image];}
                             completion:nil];

             posterImageView.tag = indexPath.row;
             posterImageView.image = image;
             [myImage insertObject:posterImageView atIndex:posterImageView.tag];
         }

        else
        {
            NSLog(@"Cached");
        }
    }
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
    {
        NSLog(@"Failed to fetch poster.");
    }];

But it always generates an error. I already allocated myImage mutable array already.


Solution

  • The index you pass to insertObject:atIndex: must be less than or equal to the current number of objects already added to the array. You can't insert objects at a random place in the array like you are doing.

    When you allocate a mutable array, even with a set capacity, the array is empty. Starting with an empty array your only options are to call addObject: or to call insertObject:atIndex: with an index of 0. Any value other than 0 (assuming the array is empty) will cause an exception.

    If you have a need to insert the objects at random locations, you must first fill the array with a set number of dummy objects, such as NSNull instances. This requires that you know what the maximum array size will be.

    NSUInteger maxSize = ... // some known maximum number of images
    NSMutableArray *myImage = [NSMutableArray arrayWithCapacity:maxSize];
    for (NSUInteger i = 0; i < maxSize; i++) {
        [myImage addObject:[NSNull null]];
    }
    

    Now you can insert your images in a random place as long as the index is less than maxSize. But now you must use replaceObjectAtIndex:withObject: instead of insertObject:atIndex:.