Peter M
Peter M

Reputation: 7513

Type of property does not match type of accessor (when subclassing)

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?

Upvotes: 1

Views: 2103

Answers (2)

djromero
djromero

Reputation: 19641

The offending line:

barney = fred.value;

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 found value with a different type causing the warning.

A solution is to write your property as:

@property (nonatomic, assign) int value;

and the enum as:

enum {
    zero = 0,
    one,
    two,
    three,
    four
};
typedef int NumberEnum;

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 NSUInteger instead, as it is 64-bits friendly.

And of course, much better if you just define the property as NumberEnum in the base class.

Upvotes: 0

Ismael
Ismael

Reputation: 3937

Your @property says int and the compiler is probably messing up with your methods. Try setting the @property type to NumberEnum and it should work (you will need to move the enum definition to your .h)

Upvotes: 1

Related Questions