Jack
Jack

Reputation: 5424

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.

Upvotes: 0

Views: 382

Answers (4)

Dr.Kameleon
Dr.Kameleon

Reputation: 22810

What you've written is equivalent to something like :

- (bool) thisIsTrue
{
      if ([self thisIsTrue])
      {
          //
      }
}

Obviously the function calls itself over and over again, creating an infinite loop and leading to a crash.

Upvotes: 0

Vladimir
Vladimir

Reputation: 170829

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;
}

Upvotes: 5

Adrian Ancuta
Adrian Ancuta

Reputation: 1036

When calling this line

if (self.stack == nil) {

it goes back into the exact method and it is created an infinite loop. Just remove the self.

Upvotes: 0

matsr
matsr

Reputation: 4267

self.stack calls the getter you are creating. By using self.stack inside the getter method, you are creating an infinite loop, which is not desirable.

Upvotes: 0

Related Questions