Objective-C 基类属性自定义 Getter 未从子类调用

标签 objective-c inheritance properties getter

基类接口(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/

相关文章:

c++ - 构造函数和继承 C++

inheritance - Swift 语言中的抽象函数

c# - 面向对象 : Using Properties and Constructor

ios - 具有多个类的 Storyboard UIViewController

ios - 在 UIPageViewController 中禁用滑动手势

iphone - 在 iPhone 上以编程方式测量网络流量

c# - 跟踪更改(未保存)的对象

iphone - 如何验证 UITextField 文本?

C++继承问题

.net - VB.NET:具有公共(public) getter 和 protected setter 的属性