I just started learning Objective-C and OOP ... so I have very stupid question :) I wanna understand how to write recursive functions in Objective-C.
I get factorial counting as example. He开发者_开发知识库re is my code )) he-he
#import <Foundation/Foundation.h>
@interface Factorial : NSObject
{
int nFact;
}
-(int) countFactorial:(int) nFact;
-(void) printFactorial;
@end //Factorial
@implementation Factorial
-(int) countFactorial:(int) n
{
int tmp;
if (n!=0)
{
tmp=n*countFactorial(n-1);
}
else {
return(0);
}
nFact=tmp;
}
-(void) printFactorial
{
NSLog(@"Factorial = %i",nFact);
}
@end //Factorial
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
id myFact=[Factorial new];
int qqq=[myFact countFactorial:5];
[myFact printFactorial];
[myFact release];
[pool drain];
return 0;
}
I get error from compiler - that I implicit declare countFactorial function and I get error (of course) from linker that it didn't find countFactorial
Plz give my any suggestions how implement recursion in Objective-C I want to use it im my next "project" - tic tac toe - to find right move via recursion )
Thx!
You are trying to call a C function, not a method on an object. To call the object's method use the following:
tmp=n* [self countFactorial:n-1];
You might want to read Apple's introduction to Objective-C to help you understand the syntax.
These are not functions, they're methods. You call them like [self countFactorial:n-1]
.
You could write a normal C function to do the same thing, though.
You need to use self
when calling methods on the same object - like this:
tmp=n*[self countFactorial:n-1];
精彩评论