0

I've written code that gathers images from JSON requests and attempts to add them to an NSMutableArray to be used later in a table view. The problem is after adding the image objects to the array, the size of my NSMutableArray is 0. Here is the relevant code:

@implementation example{
    NSMutableArray *_placeImages;
}

-(void)viewDidLoad{
    ...
    _placeImages = [[NSMutableArray alloc] init];
}

-(void)JsonQuery {
    ...
    // Retrieve the results of the URL.
    dispatch_async(kMyQueue, ^{
    [self downloadImages];
    [self performSelectorOnMainThread:@selector(reloadTableData) withObject:NULL waitUntilDone:YES];
    });
}

-(void)downloadImages{
     ...
     NSData* data = [NSData dataWithContentsOfURL: url];
    UIImage* image = [UIImage imageWithData:data];
    [_placeImages addObject:image];
}
5
  • 2
    Have you initialized your array anywhere? _placeImages = [NSMutableArray new] Commented Aug 19, 2014 at 1:51
  • Yes! I forgot to add that bit, but I do [[NSMutableArray alloc] init]. I wonder if it has to do with accessing the array from another thread. Commented Aug 19, 2014 at 23:19
  • 1
    Regardless your current problem, what you did here is not a correct way to collect and show images. I suggest you should use SDWebImage for images to show on UITableView. It is easy to deploy and use. Almost everyone use it for UITableView + Image combo. It has own caching mechanism, you do not need to download same images again and again. Commented Aug 19, 2014 at 23:34
  • @SevP Are you sure viewDidLoad is firing before downloadImages? Commented Aug 20, 2014 at 2:11
  • Yes. I've also tried alloc/init immediately before adding objects. It must've been something else buried in my code, too much too paste here. I ended up using @mohacs suggestion which completely voided the question. Thanks for the help! Commented Aug 21, 2014 at 8:09

1 Answer 1

3

you must alloc NSMutableArray first:

_placeImages = [[NSMutableArray alloc] init];

or you can using lazy init:

- (NSMutableArray *)placeImages
{
    if (!_placeImages) {
       _placeImages = [[NSMutableArray alloc] init];
    }
    return _placeImages
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. I actually do alloc and init in my viewDidLoad method, but this would certainly have been an issue.
If it not necessary to use NSMutableAarray, I recommend you using NSArray, because NSMutableArray have no thread safe. Beside, declare _placeImages as property, using lazy init and only access it with self.placeImages. Hope this can help u, good luck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.