Question

This is my first question so excuse me for being a newbie.

I am working with a CollectionView that shows images downloaded from the internet. The problem appears when I try to do it asynchronously.

@interface myViewController
{
    NSArray *ArrayOfSections
}
@end

-(void)viewDidLoad{
    [self performSelectorInBackground:@selector(refreshImages) withObject:nil];
}

-(void)refreshImages{
    ... //Get information from the net


    NSArray internetInfo = ...;

    [self performSelectorOnMainThread:@selector(refreshCollectionView:) withObject:internetInfo waitUntilDone:NO];
}

-(void)refreshCollectionView:(NSArray tempArray){

    ArrayOfSections = tempArray;

}

This code is not working. It shows an empty CollectionView, although I have double checked that the information stored on ArrayOfSections is correct.

Moreover, if I do it synchronously (I change only viewDidLoad).

-(void)viewDidLoad{
    [self refreshImage];
}

Everything works fine. I am going bananas. Please help

Was it helpful?

Solution

I think it's because you're not telling the collection view to reload. Your refresh method updates the model but not the view.

If you're fetching the data on a background thread, the main thread can continue it's lifecycle, which involves querying the collection view datasource and delegate methods then updating the view, but it will be doing this too soon in your case, as the model isn't ready. That's why you need to tell it to do that again, when the model is ready, at the end of your data fetch. Since you block the thread when doing it synchronously, it won't reach the collection view methods until the model is ready, which is why it works that way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top