Create my own completion blocks in iOS
10,009
Since you're not using any parameters in your callback, you could just use a standard dispatch_block_t and since you just want to call back to it when your long process has completed, there's no need to keep track of it with a property. You could just do this:
- (void)doSomeLongThing:(dispatch_block_t)block
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Perform really long process in background queue here.
// ...
// Call your block back on the main queue now that the process
// has completed.
dispatch_async(dispatch_get_main_queue(), block);
});
}
Then you implement it just like you specified:
[downloader doSomeLongThing:^(void) {
// do something when it is finished
}];
Comments
-
Fogmeister almost 2 years
I have an object which takes a long time to do some stuff (it downloads data from a server).
How can I write my own completion block so that I can run...
[downloader doSomeLongThing:^(void) { //do something when it is finished }];
I'm not sure how to save this block in the downloader object.
-
Fogmeister about 11 yearsThanks, I will keep this for future reference. In my actual code there are a couple of parameters and I need two different blocks. It's for the completion/error of an NSURLConnection but it's one that I can't use sendAsynch... with.
-
Matt Long about 11 yearsI see. You might also consider looking at AFNetworking in that case. There are debates as to whether these libraries make things better or not. In my opinion, the blocks based APIs make AFNetworking a very simple and convenient library to use. You can take a look at it here: github.com/AFNetworking/AFNetworking and decide for yourself.
-
Fogmeister about 11 yearsThanks. I'll take a look. I've created my class now and it seems to be working well but I'll consider it for the future.
-
marciokoko over 10 yearsCan someone take a look at my related question here: stackoverflow.com/questions/21269848/…