简体   繁体   中英

Any ideas to cancel a function in the middle? Swift iOS

I call a network task to fetch some JSON when user selects a cell in a UICollectionView . This is asynchronous so the UI remains active whilst the data is being retrieved. Allowing user to select another cell in the UICollectionView . I do not want to stop this but I do want a way to cancel the first function call and call the new method for the now selected cell.

Is there a way to in perhaps didDeselectItemAt indexPath: to cancel any currently executing tasks?

I was thinking to place a "please wait" modal view over the UI which would prevent a second cell selection until the function returned. Is this my best option or is there a better way?

By maintaining separate threads using NSOperationQueue enables controls over tasks in the middle of execution whereas GCD wont allow the same but both works for background and foreground execution of particular task mechanism.

  • GCD is a lightweight way to represent units of work that are going to be executed concurrently. You don't schedule these units of work; the system takes care of scheduling for you.

  • NSOperation adds a little extra overhead compared to GCD, but you can add dependency among various operations and re-use, cancel or suspend them.

Sample:

var backgroundQueue = NSOperationQueue()
    backgroundQueue.addOperationWithBlock(){
        println("hello from background")
        NSOperationQueue.mainQueue().addOperationWithBlock(){
            self.theLabel.text = "updated from main thread"
        }
    }

Now can do various operation provided NSOperationQueue over backgroundQueue variable.

You can use a NSOperationQueue to create and keep track of the asyncronous requests and cancel them when necessary.

See the answers to this other question here: GCD cancel async block?

You can submit your networking tasks as NSOperations to an NSOperationQueue .

NSOperation has a cancel method, and NSOperationQueue has a cancelAllOperations method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM