Reputation: 23901
Objective-C is a superset of ANSI C. In GNU C, you can nest one function in another function... like this ...
float E(float x)
{
float F(float y) //objective-C compiler says expected ; at end of declaration
{
return x + y;
}
return F(3) + F(4);
}
Is it possible to do this in Objective-C?
I know about blocks and NSInvocation objects, which could simulate the above C code. But can you define a function within the lexical scope of another function in Objective-C? Something like ...
-(int) outer:(int)x
{
-(int) inner:(int)y //use of undeclared identifier inner
{
return x * 3;
}
return inner(x);
}
Upvotes: 3
Views: 1779
Reputation: 133577
You can't simply because in ObjectiveC methods are attached to classes like in C++, this means that there is always an implicit self
inside a function.
How are you supposed to invoke a function that is nested inside another one? Making it a class method doesn't make much sense. Only way to invoke it would be by having it static (but it's seems really over complicating it)
You should use blocks, that are available to C, C++ and ObjectiveC on OS X or something similar like functors if you are going ObjectiveC++.
Upvotes: 2
Reputation: 32404
You can't, but you can easily get the same behavior with block
int outer(int i)
{
int (^inner)(int) = ^(int x)
{
return x * 3;
};
return inner(i);
}
Upvotes: 8