4

I believe what I'm trying to do is referred to as a "deferred callback" at least in some paradigms.

Basically I need a way to call a method after another method returns. Something like this:

- (void)someMethod:data
{
    [someObject doSomethingAfterCurrentMethodReturns]
}

I would like to be able to do this because a library for an external accessory that I have to use will crash the app if I do the thing I want to do within the method. This is noted in the documentation for the library. My current workaround involves an additional user interaction -- throw up UIAlertView and put the method behind a button click.

I've seen some libraries that seem to handle this. Is there a built in way to handle this in Objective C?

anthropomo
  • 4,100
  • 1
  • 24
  • 39

4 Answers4

1

I know this is old but wanted to provide an option that I like better than provided solution because I don't know if it is guaranteed to work and I didn't want to test it.

You are correct that you want defer equivalent. I too was looking for this. Other implementations suggest a custom class that leverage auto-release.

I liked this solution best as it is simple and inline:

- (void)foo {
// code to execute in foo
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    // code to execute after foo() returns
});
Cookster
  • 1,463
  • 14
  • 21
1

You can use

__attribute__((cleanup(...)))
Chris Forever
  • 678
  • 1
  • 5
  • 18
0

Depending on the number of parameters the method has you could use performSelector:withObject:afterDelay:. Or you could start an NSTimer and call the method when it fires.

Wain
  • 118,658
  • 15
  • 128
  • 151
0

I came up with a defer statement in ObjC similar to Go's defer. See my blog post and the GitHub repo. It would look like this:

- (void)someMethod:(id)data
{
  defer(^(){
    [someObject doSomethingAfterCurrentMethodReturns];
  });
  ///...
}
ricardopereira
  • 11,118
  • 5
  • 63
  • 81
Alejandro
  • 3,726
  • 1
  • 23
  • 29