2

I have a method, like so:

- (void) simpleMethod {
    var = someValue;
}

I wanted to define a function which exists only within that method (I can do this in python for example). I tried to define it like a normal C function, like this...

- (void) simpleMethod {
    var = someValue;
    int times1k(int theVar) {
    return theVar * 1000;
    }
    ivar = times1k(var);
}

But Xcode throws various errors. Is it possible to define a function within a method in Objective-C? And if so, how?

2
  • Possible duplicate of stackoverflow.com/q/2462645/1114171 Commented Jan 29, 2012 at 16:15
  • I don't think you can do that. Can't in regular C. But you might be able to fake it using blocks. Commented Jan 29, 2012 at 16:26

1 Answer 1

16

No, Objective-C follows the strict C rules on this sort of thing, so nested functions are not normally allowed. GCC allowed them via a language extension but this extension has not been carried over to Clang and the modern toolchain.

What you can do instead is use blocks, which are Objective-C's version of what Python (and most of the rest of the world) calls closures. The syntax is a little funky because of the desire to remain a superset of C, but your example would be:

- (void) simpleMethod {
    var = someValue;

    // if you have a bunch of these, you might like to typedef
    // the block type
    int (^times1k)(int) = ^(int theVar){
    return theVar * 1000;
    };

    // blocks can be called just like functions
    ivar = times1k(var);
}

Because that's a closure rather than a simple nested function there are some rules you'd need to follow for declaring variables if you wanted them not to be captured at their values when the declaration is passed over, but none that are relevant to your example because your block is purely functional. Also times1k is a variable that you can in theory pass about, subject to following some unusual rules about memory management (or letting the ARC compiler worry about them for you).

For a first introduction to blocks, I like Joachim Bengtsson's article.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for blocks and a moral +1 more for pointing to Joachim's excellent article.
Thanks for a clear answer, for using my example to demonstrate, and for the link to a thorough resource. When I have enough rep to +1, I will.

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.