Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

iphone - loading images from a background thread using blocks

I have the following method, which basically calls a request to load an array of NSData of images in the background thread:

[query findObjectsInBackgroundWithBlock:^(NSArray * objects, NSError * error){

}];

In this case objects is an array of the NSData. The issue is that if I have 100 images to load (100 elements in the array). This means that the user will have to wait for quite some time to see any image showing up in a UITableView. What I want to do is for them to see an image once it is available/loaded.. do I have to then change the code so that it does 100 background threads to load the image?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you could implement something like this in your cellForRowAtIndexPath:

That way you load each image in the background and as soon as its loaded the corresponding cell is updated on the mainThread.

      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
        NSData *data0 = [NSData dataWithContentsOfURL:someURL];
        UIImage *image = [UIImage imageWithData:data0];

        dispatch_sync(dispatch_get_main_queue(), ^(void) {
            UIImageView* imageView = (UIImageView*)[cell viewWithTag:100];
            imageView.image = image;
        });
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...