Subclasses and @property declarations
Subclasses and @property declarations
- Subject: Subclasses and @property declarations
- From: William Squires <email@hidden>
- Date: Tue, 04 Mar 2014 04:20:25 -0600
Let's say I have a simple class, CParallelogram
"CParallelogram.h"
//
// CParallelogram.h
//
#import <Foundation/Foundation.h>
@interface CParallelogram : NSObject
@property (nonatomic) CGFloat width;
@property (nonatomic) CGFloat height;
@property (nonatomic, readonly) CGFloat interiorAngle;
@property (nonatomic, readonly) CGFloat area;
-(id)initWithWidth:(CGFloat)newWidth andHeight:(CGFloat)newHeight andInteriorAngle:(CGFloat)newAngle;
@end
The implementation file is similarly simple
"CParallelogram.m"
//
// CParallelogram.m
//
#import "CParallelogram.h"
@interface CParallelogram ()
@end
@implementation
@synthesize width;
@synthesize height;
@synthesize interiorAngle;
#pragma mark "Custom Accessors"
-(CGFloat)area
{
return (_width * _height);
}
#pragma mark "Memory Management"
-(id)initWithWidth:(CGFloat)newWidth andHeight:(CGFloat)newHeight andInteriorAngle:(CGFloat)newAngle
{
if (self = [super init])
{
_width = newWidth;
_height = newHeight;
_interiorAngle = newAngle;
}
return self;
}
-(id)init
{
// Assumes there's a #define PI 3.1415926 somewhere...
return [self initWithWidth:0.0f andHeight:0.0f andInteriorAngle:(PI / 4.0)];
}
@end
Now, I create a subclass, CRectangle : CParallelogram, and then I subclass CRectangle to get CSquare. CRectangle is simple enough and won't be shown here, save to say that it's public initWith...() method only takes two parameters and defaults interiorAngle to 90 degrees (pi / 4). Likewise, CSquare has a public initWith...() that only takes a side length. In CSquare, I override the public @property (nonatomic, readonly) CGFloat area (first defined in CParallelogram) in CSquare.m to simply be
...
#pragma mark "Custom Accessors"
-(CGFloat)area
{
return (_width * _width);
}
...
Question: Do I have to list the @property line in CSquare.h in order for users of CSquare to be able to access the "area" property? Or is it sufficient that (because I'm overriding it, and it has the same method signature - i.e. selector) the superclass CParallelogram has already declared it?
2nd Question: If I stick CParallelogram instances (well, references, really), or subclasses thereof into a collection object (NSArray, NSDictionary, etc...) and I later iterate over them, asking for their areas, will I get the correct polymorphic behavior (i.e. the selector mechanism will correctly point to the subclass instance and send the "area" message there), or do I have to pull the reference out of the collection, test and typecast it, then call for its area?
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden