This question already has an answer here:
- How to do sparse array in Cocoa 4 answers
In my app, I am trying to be able to download two objects, one 'article' and one image, from my server. The 'article'-object (translated from sql-query to a subsubclass of NSObject) has a pointer to where to download the image, which obviously takes longer to download than the article-query. When I 'download' the articles, they end up in an NSArray
. When they are complete, then I am iterating through the array to start asynchronous downloads of each image, kind of like this:
for(Article *a in articles)
{
NSString *url = a.imageURL;
//Start async download of this image
}
I'm using Parse Framework to do this, so the block would probably look weird to people who haven't used it, so I'll just explain instead: In the block (when the async download is finished), I am assigning the returned NSData (the image) to another array, an NSMutableArray
named articleImages
, and I want the index of the image in this array to correspond to the index of the article in the other; the same chronology in both arrays.
For now, I'm doing this: [articleImages insertObject:data atIndex:i];
(where i
comes from the for-loop, not really using foreach as above) because the block is still inside the same for-loop. This is working for now, but I've only tested with three articles so far. If I'm not completely wrong here, this is a poor and flawed way of doing this, as for the scenarios that image2 is downloaded faster than image1, even though it was started a tiny bit later. In those cases, I imagine I would stumble upon an exception saying I can't insert objects at index:2
in an empty array.
I was thinking about filling an array with dummy data, with the size [articles count]
, and later replace the correct-index (i
) dummy data with the downloaded images as they come in in random order. But I feel dirty by even thinking of this. There has to be a proper way to do this? I'm not completely sure what to search for either..
image
of typeUIImage
to yourArticle
class and then set this property to the downloaded image once the download is finished? – s1m0n Jul 30 '13 at 18:57