Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does iPhone SDK Objective C support functions inside of functions?

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?

like image 400
Moshe Avatar asked Mar 17 '10 13:03

Moshe


3 Answers

A bit late, but you can place an inline block into a function, which kind of acts like your nested function questions.

-(int)addNumbers:(int)a withB:(int)b withC:(int)c {

    // inline block
    int(^inlineaddNumbers)(int, int) = ^(int a, int b) {
        return a + b;
    };

    if( a == 0 ) return inlineaddNumbers(b,c);
    else return inlineaddNumbers(a,c);   
}

It's a bit messy, but it works!

like image 134
Gui13 Avatar answered Oct 22 '22 05:10

Gui13


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

like image 33
Paul R Avatar answered Oct 22 '22 06:10

Paul R


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";"

like image 8
Frank Shearar Avatar answered Oct 22 '22 05:10

Frank Shearar