【发布时间】:2013-08-07 15:32:29
【问题描述】:
当我只在超类中声明 @property 而不声明 ivars 时,将其子类化并尝试在子类中使用超类 ivar (_propertyName) 实现 getter,xcode 会调用错误声明 Use of undeclared identifier '_propertyName'。
符合最佳编程实践的解决方案是什么?
我应该在子类的@implementation中@synthesize propertyName = _propertyName还是
@interface SuperClass : AnotherClass
{
Type *_propertyName;
}
@property Type *propertyName;
@end
编辑:
我确实了解属性访问器方法的自动“综合”以及编译器创建“下划线 ivars”。
ivar 可以从 SuperClass 的实现访问,而无需在接口或实现部分中声明任何 @synthesize 或 ivars 声明。
进一步澄清我的情况: 免责声明:内容从 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
【问题讨论】:
-
这很奇怪:在 Objective C 中,ivars 默认是受保护的,所以你的子类应该能够像访问它们一样访问它们。你如何访问
_propertyName来得到那个错误? -
如果您的属性是
@property Type *_propertyName;,那么我认为ivar 将是__propertyName。 (两个下划线)为什么你的子类需要直接访问 ivar? -
仅供参考,不再需要
@synthesize属性;只需在头文件中声明它们,合成由 Xcode/编译器自动完成。 -
抱歉,我更正了错字。 ivar 是自动创建的,但只能由超类直接访问。
-
@BergQuester 我在 SuperClass 中使用 ivar 来存储一个对象,该对象在子类的实现中是该对象的子类。
标签: objective-c properties subclass