How to overwrite parent properties (redeclaration of parent property as a static variable)?

StackOverflow https://stackoverflow.com/questions/17773150

문제

It is possible to have a type in the parent class that the subclass overwrites?

The idea here would be to have a shape class, with subclasses of rectangles, square, circles, etc. Wondering if it's possible to overwrite the definition of 'shapeType' int property in the parent class. Something like this?

e.g. in globals.h

#define kShapeType_Rectangle = 1
#define kShapeType_Square = 2
#define kShapeType_Triskaidecagon = 13 // try pronouncing this!

in shape.h

@interface shape : NSObject
   @property int shapeType;
   @property int shapeID;
   @property UIColor shapeColor;
@end
....

in rectangle.h

#import globals.h

@interface rectangle : shape
    @property static (nonatomic, readonly) int shapeType = kShapeType_Rectangle;  // how do I get this working?
@end

So two questions:

1) Is such a thing possible - i.e. redeclaration of parent property as a static variable

2) Yes or No to (1), is this the best coding style for this sort of thing? I'm not experienced in Obj-C patterns, but if one exists, could someone suggest a source for me to look at please?

Thanks a lot!

도움이 되었습니까?

해결책

There is no concept of an Objective-C property being a static variable. An Objective-C property is just a syntax shorthand for declaring two methods, a getter and a setter (or just a getter in the case of readonly properties). You can override either or both of those methods in a subclass and have them get and set the value from/to a static variable/value in the subclass if you want. There's nothing preventing that.

In this case you would do this:

- (int)shapeType
{
    return kShapeType_Rectangle;
}

Not to get too philosophical, but having such a property would seem to be creating a redundancy with the type system. Put differently, why have a property that you have to override in every subclass? In this case why have shapeType return kShapeType_Rectangle when you know the instance is a rectangle by virtue of it being of the rectangle class?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top