I have a set up where I have a hierarchy of view types with an equivalent hierarchy of model types. The set up is as follows:
The node model / data:
@interface GenericNode : NSObject
//blah blah blah
@end
@interface ShapeNode : GenericNode
//more blah
@end
the nodeViews, which will always receive an equivalently typed node as its model:
@interface GenericNodeView : UIView
@property (nonatomic, strong) GenericNode * model;
@end
@interface ShapeNodeView : GenericNodeView
@end
However, the problem here is that the type of the model
is always retained as the abstract superclass, forcing me to cast it every single time I want to access methods of properties of the subclasses.
Is there a way to recast class properties such that exampleShapeNodeView.model
always returns an instance of ShapeNode
and so on?
I have tried custom accessor methods such as
@interface GenericNodeView : UIView
@property (nonatomic, strong) GenericNode * model;
-(GenericNode *)myModel;
@end
@interface ShapeNodeView : GenericNodeView
-(ShapeNode *)myModel;
@end
//in genericNodeView implementation
-(GenericNode *)myModel{
return (GenericNode *) self.model;
}
//in shapeNodeView implementation
-(ShapeNode *)myModel{
return (ShapeNode *) self.model;
}
but calling [exampleShapeNodeView myModel]
still returns a GenericNode
;
I just tested this out, and it worked great for me:
In the child class, redeclare with the @property:
@interface GenericNodeView : UIView
@property (nonatomic, strong) GenericNode * model;
@end
@interface ShapeNodeView : GenericNodeView
@property (nonatomic, strong) ShapeNode * model;
@end
You need to re-@synthesize as well, but there were no complaints by my Xcode (4.3.3)