Convenience constructor

//laborious
NSNumber* zero_a = [[NSNumber alloc] initWithFloat:0.0f];

[zero_a release];

//handier
NSNumber* zero_b = [NSNumber numberWithFloat:0.0f];

//no need of release



//The Vehicle class
@interface Vehicle : NSObject
{
NSColor* color;
}
-(void) setColor:(NSColor*)color;
+(id) vehicleWithColor:(NSColor*)color;     //convenience constructor
@end





//bad convenience constructor
+(Vehicle*) vehicleWithColor:(NSColor*)color
{
//the value of “self” should not change here
self = [[self alloc] init]; // ERROR !
[self setColor:color];
return [self autorelease];
}


//Almost perfect constructor
+(id) vehicleWithColor:(NSColor*)color
{
id newInstance = [[Vehicle alloc] init]; // OK, but ignores potential sub-classes
[newInstance setColor:color];
return [newInstance autorelease];
}

@implementation Vehicle
+(id) vehicleWithColor:(NSColor*)color
{
id newInstance = [[[self class] alloc] init]; // PERFECT, the class is
                                                                              // dynamically identified
[newInstance setColor:color];
return [newInstance autorelease];
}
@end


@interface Car : Vehicle {…}
@end

//produces a (red) car
id car = [Car vehicleWithColor:[NSColor redColor]];

Leave a Reply