Recursion in Objective-C

Our example demonstrates recursion in Objective-C. Here’s the implementation:

#import <Foundation/Foundation.h>

@interface Recursion : NSObject

+ (NSInteger)factorial:(NSInteger)n;

@end

@implementation Recursion

+ (NSInteger)factorial:(NSInteger)n {
    if (n == 0) {
        return 1;
    }
    return n * [self factorial:n - 1];
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSLog(@"%ld", (long)[Recursion factorial:7]);
        
        // Objective-C doesn't have closures, but we can use blocks
        // which are similar. However, recursive blocks require a 
        // separate declaration.
        NSInteger (^fib)(NSInteger);
        fib = ^NSInteger(NSInteger n) {
            if (n < 2) {
                return n;
            }
            return fib(n - 1) + fib(n - 2);
        };
        
        NSLog(@"%ld", (long)fib(7));
    }
    return 0;
}

This factorial method calls itself until it reaches the base case of factorial(0).

In Objective-C, we don’t have closures like in some other languages, but we have blocks which are similar. However, for recursive blocks, we need to declare the block separately before defining it, as shown in the fib block above.

To run the program, compile it and then execute:

$ clang -framework Foundation recursion.m -o recursion
$ ./recursion
5040
13

The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).

Objective-C combines features of C with object-oriented programming concepts, which gives it a unique syntax compared to some other languages. The use of brackets [] for method calls and the @ symbol for language-specific keywords are characteristic of Objective-C.