[英]Objective C - Custom Getter with inheritance
最近,我与Core Data合作。 当我想为某些字段设置默认值时,我想到了这个问题:
所以我做了一个简单的表示:
我们有2类Parent和Child,其中Child继承自Parent。
// Parent.h
@interface Parent : NSObject
@property (strong, nonatomic) NSString *lastName;
// Child.h
@interface Child : Parent
在Parent类中,我做了一个自定义的吸气剂,以在未设置任何内容时设置默认值:
// Parent.h
- (NSString *)lastName
{
if (_lastName) {
return _lastName;
} else {
return @"Parent Default Name";
}
}
但是我无法为Child从其Parent继承的“名称”字段设置自定义默认值。
// Child.h
@implementation Child
- (NSString *)lastName
{
if (super.lastName) {
return super.lastName;
} else {
return @"Child Default Name";
}
}
要测试的主要函数:int main(int argc,const char * argv []){
@autoreleasepool {
Parent *newParent = [[Parent alloc] init];
newParent.lastName = @"newParentName";
NSLog(@"Parent: %@", newParent.lastName);
Child *newChild = [[Child alloc] init];
NSLog(@"Child: %@", newChild.lastName);
}
return 0;
}
显然,@“儿童默认名称”永远不会到达。 返回的值将是@“父默认名称”。 所以我的问题是:如何在不定义重写属性的情况下为Child类从Parent继承的字段设置自定义getter?
// Parent.h
@interface Parent : NSObject
{
NSString *_lastName; //just add this line.
}
@property (strong, nonatomic) NSString *lastName;
如果要使用其他名称,可以尝试以下操作:
// Parent.h
@interface Parent : NSObject
{
NSString *_lastNameAlias; //can be used in child
}
@property (strong, nonatomic) NSString *lastName;
//Parent.m
@synthesize lastName = _lastNameAlias;
// Parent.m
- (NSString *)lastName
{
if (!_lastName) {
_lastName = @"Parent Default Name";
}
return _lastName;
}
// Child.m
- (NSString *)lastName
{
if (!_lastName) { //Or _lastNameAlias
_lastName = @"Child Default Name";
}
return _lastName;
}
正如史蒂芬·费舍尔(Steven Fisher)所述, lastname
与lastName
不同,但我认为这是一个拼写错误。
注意:
- (NSString *)lastname
VS
- (NSString *)lastName
Objective-C区分大小写。 确保它们具有相同的大小写,并且所需的行为应自动发生。
就是说,调用self.lastName
很奇怪(假设您都选择了lastName
)。 我不确定是否可以。 我建议改为调用[super lastName]
。
问题在于lastName
方法的父实现从不返回nil
。 它要么返回_lastName的当前(非nil)值,要么返回默认的父字符串。 在任何情况下都不会返回nil
。 因此, if [super.lastName]
检查将始终返回true。
为避免此问题,子获取器需要直接访问实例变量。 仅当父类在头文件中显式声明实例变量时,才可以这样做。 所以parent.h
应该是
@interface Parent : NSObject
{
NSString *_lastName;
}
@property (strong, nonatomic) NSString *lastname;
@end
然后在child.m
的实现可以是
- (NSString *)lastname
{
if ( _lastName )
return( _lastName );
else
return @"Child default name";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.