Search code examples
objective-ciosxcodegetterself

Why can't I initialize getter this way in Objective C?


I'm a bit confused why I can't initialize a getter this way:

@synthesize stack = _stack;

- (NSMutableArray *) stack
{
    if (self.stack == nil) {
        self.stack = [[NSMutableArray alloc] init];
    }
    return self.stack;
}

I know that if I replace self.stack with _stack, it will work perfectly fine, but I just don't know why I can't use self.stack. I use self.stack later on in the code without problem though.


Solution

  • The problem is in following line:

    if (self.stack == nil) 
    

    which is equivalent to

    if ([self stack] == nil)
    

    So you're calling your getter method inside itself and that results in infinite recursion. You can remove calling the getter by addressing the ivar itself:

    - (NSMutableArray *) stack
    {
        if (_stack == nil) {
            _stack = [[NSMutableArray alloc] init];
        }
        return _stack;
    }