When I just declare a @property
in a superclass without declaring ivars, subclass it and try to implement getter using the superclasses ivar (_propertyName
) in subclass, xcode invokes an error stating Use of undeclared identifier '_propertyName'
.
What is the solution conforming to best programming practices?
Should I @synthesize propertyName = _propertyName
in the @implementation
of the subclass or
@interface SuperClass : AnotherClass
{
Type *_propertyName;
}
@property Type *propertyName;
@end
EDIT:
I do understand the automatic "synthesis" of the properties' accessor methods and creation of "underbar ivars" by the compiler.
The ivar is accessible from the implementation of the SuperClass
without any @synthesize
or declaration of ivars in the interface or implementation section.
Further clarification of my case: Disclaimer: Contents stolen block of code from Alfie Hanssen
@interface SuperViewController : UIViewController
@property (nonatomic, strong) UITableView * tableView; // ivar _tableView is automatically @synthesized
@end
#import "SuperViewController.h"
@interface SubViewController : SuperViewController
// Empty
@end
@implementation SubViewController
- (void)viewDidLoad
{
NSLog(@"tableView: %@", self.tableView); // this is perfectly OK
}
// ************* This causes problem **************
- (UITableView *) tableView {
if (!_tableView) { // Xcode error: Use of undeclared identifier '_propertyName'
_tableView = [[SubclassOfUITableView alloc] init];
}
return _tableView;
}
// ************************************************
@end
If you want to use an ivar in both the superclass and the subclass, you have to declare it in the interface of the superclass, because it's the only file that's included in both implementations. Otherwise, you're just trying to guess what could be in the implementation of the superclass and xcode will not play game.
The above is true whether there is a property that use that ivar or not.
Now if you have a property in the superclass and you write in the subclass implementation :
@synthesize propertyName = _propertyName
You're just saying that you're ditching whatever implementation of that property was in the superclass and you want the standard setter and getter generated by xcode, working on an ivar named _propertyname. Maybe the superclass works the same way, maybe not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With