0

What I have is an array of url's that point to images and a corresponding array of the names of the images

For example ['www.pictures/dog.jpg', 'www.pictures/lamp.jpg', 'www.pictures/piano.jpg'] ['dog', 'lamp', 'piano']

I want each cell to have a the picture with the corresponding word. My problem is that the pictures almost always appear out of order. How I have it now, the words appear in order.

Anyone have an idea of how to get my images appear in order

- (photoCollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    photoCollectionViewCell *photoCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"photoCell" forIndexPath:indexPath];

    if(self.photoIndex == (self.totalPhotos)) {
        self.photoIndex = 0;
    }

    NSURL *url = [NSURL URLWithString:self.imageURLArray[self.photoIndex]];
    NSString *word = self.phraseWordsArray[self.photoIndex];

    photoCell.photoImageView.image = [UIImage imageNamed:@"icn_default"];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{
            photoCell.photoImageView.image = image;
            photoCell.photoLabel.text = word;
        });
    });



    self.photoIndex++;
    return photoCell;
}
kinezu
  • 1,212
  • 2
  • 12
  • 23
  • If your words are unique and always included in the relevant url you could just do something like url = [NSURL URLWithString:[NSString stringWithFormat:@"www.pictures/%@.jpg", word]]; – Tim Mar 16 '15 at 01:42
  • Unfortunately, the words are never in the url :( – kinezu Mar 16 '15 at 02:12
  • No worries. I would try setting both the url and word inside the dispatch_asynch. Depending on how many rows you have in your tableView you may want to also tag each cell so they don't get reused and change images etc. [See this post](http://stackoverflow.com/a/15668366/1722214) – Tim Mar 16 '15 at 04:41

1 Answers1

0

When you are using dispatch_queue_t to request data, iOS system would perform the queue randomly since the best performance. therefore your order is not what you expected.

reference: https://developer.apple.com/library/prerelease/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/index.html

Steve Lai
  • 633
  • 1
  • 7
  • 18