Pregunta

I have an array of type NSArray as below:

@property (nonatomic, strong) NSArray *myArray;

In the setter of this array, I want to check if the array count is 0, then return nil else return the array as it is. I am doing it as below:

- (NSArray *)myArray
{
    return ([self.myArray count] == 0) ? nil : self.myArray;
}

I am not getting any build error if I return nil for an NSArray, but its giving me run time error of bad access code. What mistake am I making here?

¿Fue útil?

Solución

Your getter method is recursively calling itself, because

self.myArray

is translated by the compiler to

[self myArray]

This causes a stack overflow (!) eventually.

Inside a setter or getter method of a property, you have to access the associated instance variable instead, e.g.

- (NSArray *)myArray
{
    return ([_myArray count] == 0) ? nil : _myArray;
}

Otros consejos

Do you instantiate the array anywhere else prior to calling this method? It will have to exist before you can access it.

_myArray = [NSArray arrayWithObjects:@"one",@"two",nil];

or one of the many other techniques to create an Array.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top