Pages

Thursday, January 12, 2012

Aborting performSelectorInBackgroud:withEvent

First of all, happy 2012. Our best wishes to all of our readers in this new year.

Once again we have to apologize our readers for the lack of updates, but we have a lot of work, maybe there will be some changes in our work and we don't have so much time to update the blog.

Today's entry is not a code snippet as usual, is a little trick for when we are performing any task in background and we want to cancel it. For example, I want to accomplish it when a user taps back button during an array data loading performing in background.

The only way to abort a background task is to define a class boolean variable accesible for any method.

BOOL cancelBackgroundTask

set it to NO when you lauch the task

cancelBackgroundTask = NO;
[self performSelectorInBackground:@selector(bgTask) withObject:nil];

If the user makes any action that should abort the background task, just change the boolean value

cancelBackgroundTask = NO;

And at last, in background task you have to check this variable periodically with an NSTimer or a worse approach but maybe usefull is to check it before perform any action.

if (!cancelBackgroundTask)
    [self loadData];

if (!cancelBackgroundTaks)
    [self presentData];

In this easy way you could abort a background task. This derived of the lack of a function to abort or cancel directly a thread.

I hope this help, enjoy it!

1 comment:

  1. Attractive section of content. I just stumbled upon your blog and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Anyway I will be subscribing to your feeds and even I achievement you access consistently fast.
    Chevy/Ford/Mopar Chrome Aluminum Rear View Mirror - Flamed

    ReplyDelete