Re: Problem overriding a factory class mehtod
Re: Problem overriding a factory class mehtod
- Subject: Re: Problem overriding a factory class mehtod
- From: Shawn Erickson <email@hidden>
- Date: Thu, 02 Nov 2006 16:14:07 -0800
On Nov 2, 2006, at 3:48 PM, Alan Smith wrote:
Simple, use NSObjects poseAsClass: in main or somwhere near "the
begining."
Not really a good recommendation (for several reasons).
On Nov 2, 2006, at 3:14 PM, Ivan Kourtev wrote:
I am faced with the following situation involving inheritance:
Class FooB inherits from class FooA. Class FooA implements a class
method
+ (FooA*)fooWithInt:(int)x;
The problem seems to arise with calls such as [FooB fooWithInt:x].
If I don't implement + [FooB fooWithInt], then I just get back a
FooA object (doesn't have FooB's variables).
If I override
+ (FooB*)fooWithInt:(int)x {
return [super fooWithInt:x];
}
then I get back a FooA object again.
So what is the "by-the-book" correct way to handle such
situations? I suppose a full reimplementation of + [FooB
fooWithInt] (one that doesn't call [super ...]) would do but then I
am not able to reuse the superclass's code. Not a problem in my
case (I own all classes) but what if I were working with another
party's library and a header file?
Two ways come to mind...
======== FIRST WAY ========
@implementation FooA
+ (id) fooWithInt:(int)x
{
return [[[self alloc] initWithInt:x] autorelease]; // "self" will be
the class that was sent the message, FooB if [FooB fooWithInit]
}
- (id) initWithInt:(int)x
{
self = [super init];
if (self != nil) {
....init FooA stuff...
}
return self;
}
@end
...if needed also have the following...
- (id) initWithInt:(int)x
{
self = [super initWithInt:x];
if (self != nil) {
....init FooB stuff...
}
return self;
}
@end
======== SECOND WAY ========
@implementation FooA
+ (FooA*) fooWithInt:(int)x
{
return [[[FooA alloc] initWithInt:x] autorelease];
}
- (FooA*) initWithInt:(int)x
{
self = [super init];
if (self != nil) {
....init FooA stuff...
}
return self;
}
@end
@implementation FooB
+ (FooB*) fooWithInt:(int)x
{
return [[[FooB alloc] initWithInt:x] autorelease];
}
...if needed also have the following...
- (FooB*) initWithInt:(int)x
{
self = [super initWithInt:x];
if (self != nil) {
....init FooB stuff...
}
return self;
}
@end
-Shawn
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden