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
934 views
in Technique[技术] by (71.8m points)

ios - GCD cancel async block?

I have regular code for loading images in table view cells

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        NSImage *image = file.image;
        dispatch_async(dispatch_get_main_queue(), ^{
            imageView.image = image;
        });
    });

The problem is when I scroll too fast I can see that last block fires several times on same imageView. And that looks really weird. Is there any way to cancel all previously scheduled operations for one imageView (lets say they all will have unique id) before scheduling new one?

I mean, I want to be sure that only last scheduled operation should be executed and all all previously scheduled should be dropped. Is that possible by means of Grand Central Dispatch? Or I have to add my own atomic flags to imageView objects and check whether flags are set before calling imageView.image = image;

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

To archieve it using GCD you have to use your own atomic flag.

But there is a better solution where you have cancellation of tasks out of the box. It is a NSOperationQueue.

You can read everything you need under this link: http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues


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

...