基类接口(interface):
@interface Base : NSObject
@property (nonatomic, readonly, getter=getPriceForListing) double_t priceForListing;
@end
基类实现:
@implementation Base
-(double_t)getPriceForListing
{
if (self.listPriceLow > 0 && self.listPriceHigh > 0)
{
return self.listPriceLow;
}
else if (self.listPriceLow > 0)
{
return self.listPriceLow;
}
else if (self.listPriceHigh > 0)
{
return self.listPriceHigh;
}
else
{
return self.currentPrice;
}
}
@end
子类接口(interface):
@interface Subclass : Base
@end
子类实现:
@implementation Subclass
@dynamic priceForListing;
@end
如何使用子类:
Subclass *sub = [[Subclass alloc] init];
NSLog(@"%@", sub.priceForListing);
我在这里遇到的问题是 sub.priceForListing
总是返回零,并且基类 getter 永远不会被调用,至少没有断点被击中。
最佳答案
您将“getter”定义为 getPriceForListing
,但尝试使用 priceForListing
访问它。只需省略自定义名称即可。
将“getter”方法重命名为priceForListing
。
如果没有后备实例变量,则永远不会设置它,您可以将其指定为只读
。
正如评论中提到的:删除:@dynamicpriceForListing;
。
仅供引用:在 Objective-C/Cocoa 中,“get”前缀按照惯例保留给通过引用返回值的方法。 Getter 没有“get”前缀。
关于Objective-C 基类属性自定义 Getter 未从子类调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29014548/