如何使用类在Objective-C中编写递归?

Ser*_*nsk 1 recursion objective-c

我刚开始学习Objective-C和OOP ......所以我有一个非常愚蠢的问题:)我想了解如何在Objective-C中编写递归函数.

我以阶乘计数为例.这是我的代码))他 - 他

#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;
}
Run Code Online (Sandbox Code Playgroud)

我从编译器得到错误 - 我隐式声明countFactorial函数,我从链接器得到错误(当然)它没有找到countFactorial

Plz给出了我在Objective-C中如何实现递归的任何建议我想在下一个"项目"中使用它 - tic tac toe - 通过递归找到正确的移动)

谢谢!

Col*_*son 6

您正在尝试调用C函数,而不是对象上的方法.要调用该对象的方法,请使用以下命令:

tmp=n* [self countFactorial:n-1];
Run Code Online (Sandbox Code Playgroud)

您可能希望阅读Apple 对Objective-C介绍,以帮助您理解语法.