I have the following class and subclass:
@interface NSHigh : NSObject
@property (nonatomic, strong) NSArray *array;
@end
@implementation NSHigh
-(NSArray*)array
{
_array = [[NSArray alloc] init];
return _array;
}
@end
@interface NSLow : NSHigh
@end
@implementation NSLow
/* synthesizing makes the assertion FAIL. NO synthesizing makes the assertion PASS */
@synthesize array;
@end
Then I run this code somewhere:
NSLow *low = [[NSLow alloc] init];
assert(low.array);
So, apparently, if in the subclass NSLow I synthesize the array property, then the getter from the super class does not get called, and the assertion fails.
If I do not synthesize, then the superclass getter is called, and the assertion passes.
- Why does this happen?
- How would I access the array instance variable in the
NSLowsubclass without callingself.arrayevery time?
@synthesizeinNSLowwill create the following getter:So, your array is never initialized and
nilis returned.You generally shouldn’t use
@synthesizefor@propertiesthat are declared in a superclass.Also, you shouldn’t implement a getter like the one in
NSHigh. If you want to init that array lazily you should do it like this:Finally, you shouldn’t use
NSprefix.EDIT:
If you want direct access to your ivar in the subclass, you can explicitly declare it in the header like this:
This will allow you to access the ivar in your subclasses too.