简体   繁体   中英

Objective-C Base Class Property Custom Getter Not Being Called From Subclass

Base Class Interface:

@interface Base : NSObject

@property (nonatomic, readonly, getter=getPriceForListing) double_t priceForListing;

@end

Base Class Implementation:

@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

Subclass Interface:

@interface Subclass : Base

@end

Subclass Implementation:

@implementation Subclass

@dynamic priceForListing;

@end

How subclass is used:

Subclass *sub = [[Subclass alloc] init];
NSLog(@"%@", sub.priceForListing);

The problem I am having here is that sub.priceForListing always returns zero and the base class getter is never being called, at least no breakpoint is being hit in there.

You defined the "getter" as getPriceForListing but are trying to access it with priceForListing . Just omit the custom name.

Rename the "getter" method to priceForListing .

If there is no backing instance variable, IOW it is never set you can specify it to be readonly .

As mentioned in the comments: Delete: @dynamic priceForListing; .

FYI: In Objective-C/Cocoa the "get" prefix is reserved by convention for methods that return a value by reference. Getters do not have a "get" prefix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM