OK I know that this subject has been mentioned many times before on SO, but after checking several such questions, none have talked about the issue I am having with regards to overriding the base class getters/setters in a subclass.
My base class is:
#import <Foundation/Foundation.h>
@interface BaseClass : NSObject
@property (nonatomic, assign) int value;
@end
@implementation BaseClass
@synthesize value;
@end
From that I want the subclass to act as a shim and map the “value” from an int to an enum in my child class:
#import <UIKit/UIKit.h>
#import "BaseClass.h"
typedef enum {
zero = 0,
one,
two,
three,
four
} NumberEnum;
@interface ChildClass : BaseClass
-(void)setValue:(NumberEnum)newValue;
-(NumberEnum)value;
@end
@implementation ChildClass
-(void)setValue:(NumberEnum)newValue
{
[super setValue:(int)newValue];
NSLog(@"Child Setter");
}
-(NumberEnum)value
{
NSLog(@"Child Getter");
return (NumberEnum)[super value];
}
@end
And I test this code using:
ChildClass* fred = [[ChildClass alloc] init];
NumberEnum barney;
fred.value = one;
barney = fred.value;
barney = [fred value];
XCode (4.5.2) generates the warning
Type of property ‘value’ does not match type of accessor ‘value’
On this line only:
barney = fred.value;
When the code is run, I see the log messages for both the Child Setter and Getter. So what should I be doing to eliminate this warning, and why am I getting it in the first place?
The offending line:
tells the compiler you want to use the property
value. As your child class doesn’t define it, it goes up to the base class. It foundvaluewith a different type causing the warning.A solution is to write your property as:
and the enum as:
This way synthesized property methods and your own implementations are working with the same data type. You can use symbolic values and there is no warning.
I suggest using
NSUIntegerinstead, as it is 64-bits friendly.And of course, much better if you just define the property as
NumberEnumin the base class.