views:

264

answers:

2

I know that javascript, for example supports functions inside of functions, like so:

function doSomething(){

  function doAnothingThing(){
    //this function is redefined every time doSomething() is called and only exists inside doSomething()    
  }

  //you can also stick it inside of conditions

  if(yes){
    function doSomethingElse(){
      //this function only exists if yes is true
    }
  }


}

Does objective-c support this? Theoretical example:

 -(void) doSomething:(id) sender{
   -(void) respondToEvent: (id) sender{
     //theoretically? ... please?
   }
}

BONUS: What is the proper term for a "local" function?

+5  A: 

The usual term is nested function. gcc supports nested functions as an extension to C (disabled by default). I don't think this option is available with Objective-C (or C++) with gcc though, and even if it were it's probably not a good idea to use it (portability etc).

gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html

Paul R
+3  A: 

By default Xcode disallows nested functions.

If you want to switch them on, open up the Info for your project, go to the Build tab, and set "Other C flags" (under the section titled "GCC 4.2 - Language") to "-fnested-functions".

(This is stored in your project.pbxproj file as "OTHER_CFLAGS = "-fnested-functions";"

Frank Shearar
+1 for instructions on enabling
Moshe
Note that this only works for C, I believe - not Objective-C or C++.
Paul R
@Paul you can nest a C function inside an Objective-C method just fine. You can't nest a method inside another method, but that makes sense. Objective-C's a very thin runtime on top of plain C (or C++).
Frank Shearar
@Frank: thanks - I didn't know that.
Paul R