15

What is the syntax to declare a C function that returns an Objective-C block? Is it possible?

I thought it should be something like

(void (^)(void)) myFunctionReturningABlock();

but that won't compile.

3
  • 1
    When you say doesn't work, could you elaborate a little? Does it break at runtime or does it generate a compiler error or warning? Let us know what "doesn't work" means and we can help you further. Commented Nov 28, 2011 at 14:05
  • 2
    possible duplicate of Objective-C Block type as return value Commented Nov 28, 2011 at 14:08
  • @Jasarien Sorry, I'm getting lazy. Fixed. Commented Nov 29, 2011 at 15:08

1 Answer 1

16

The syntax for your function is slightly incorrect.

As I understand it, you should define your block as a type which you can use as the return type for your function like this:

typedef void(^MyAwesomeBlock)(void);

MyAwesomeBlock blockFunction()
{
    MyAwesomeBlock block = ^{
        //some code;
    };

    return block;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that works perfectly. I also tried the 'typedef-less' version in the linked possible duplicate, but having a typedef makes it so much clearer.
Is there a typedef-less version of this?
@nielsbot if you read the comment just above yours, you'll notice that Nick refers to a typedef-less linked in a comment on the question, further up the page. But as Nick says, using a typedef makes the code much more readable - you generally don't want a typedef-less version, unless you want messy unreadable code?? :/
oh.. I looked for it here... I see it's in an answer to a question linked to via a comment on this question ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.