user890207
user890207

Reputation: 519

My UICollectionView does not update if I use async way to get data

If I use the following way to get data, it works fine. The UICollectionView shows the items properly.

NSURL *articleUrl = [NSURL URLWithString:url];
NSData *articleHTMLData = [NSData dataWithContentsOfURL:articleUrl];
<Process data here>
....
_objects = newArticles;

_objects will be feed to UICollectionView.

However, if I use the following async way to get data, the UICollectionView does not show anything.

dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
dispatch_async(myQueue, ^{
    // Perform long running process
    NSURL *articleUrl = [NSURL URLWithString:url];
    _articleHTMLData = [NSData dataWithContentsOfURL:articleUrl];

    dispatch_async(dispatch_get_main_queue(), ^{
        <Process data here>
        ....
        _objects = newArticles;
    });
});

Did I miss something?

Thanks.

Upvotes: 1

Views: 839

Answers (3)

Rinat Khanov
Rinat Khanov

Reputation: 1576

You need to manually refresh UICollectionView after receiving new data.

- (void) reloadData {

    [self.collectionView performBatchUpdates:^{
            [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    } completion:nil];
}

Call this method inside

dispatch_async(dispatch_get_main_queue(), ^{
        <Process data here>
        _objects = newArticles;
        [self reloadData];
});

Upvotes: 2

Toseef Khilji
Toseef Khilji

Reputation: 17409

Try to do Process in myQueue and only UI update in dispatch_get_main_queue

dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
dispatch_async(myQueue, ^{
    // Perform long running process
    NSURL *articleUrl = [NSURL URLWithString:url];
    _articleHTMLData = [NSData dataWithContentsOfURL:articleUrl];
   <Process data here>
        ....
    dispatch_async(dispatch_get_main_queue(), ^{

        _objects = newArticles;
    });
});

And i think you have to reload your view,

    [CollectionView reloadData];

If i am wrong correct me .

Upvotes: 0

Segev
Segev

Reputation: 19303

Where those lines of code are located? Inside viewDidLoad? Any way, after you get your data you'll need to reload your UICollectionView add:

[_yourCollectionView reloadData];

Right after:

_objects = newArticles;

Upvotes: 0

Related Questions