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.
"Deferred Callback" in Objective C
-
24-06-2022 - |
質問
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?
解決 3
他のヒント
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
});
You can use
__attribute__((cleanup(...)))
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];
});
///...
}