开发者

How to code recursion in Objective-C with classes?

开发者 https://www.devze.com 2022-12-15 04:47 出处:网络
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 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];
0

精彩评论

暂无评论...
验证码 换一张
取 消