Nested factory methods in Objective-C

Posted by StephenT on Stack Overflow See other posts from Stack Overflow or by StephenT
Published on 2010-03-21T21:43:00Z Indexed on 2010/03/21 21:51 UTC
Read the original article Hit count: 359

Filed under:
|
|
|

What's the best way to handle memory management with nested factory methods, such as in the following example?

@implementation MyClass

+ (MyClass *) SpecialCase1
{
    return [MyClass myClassWithArg:1];
}

+ (MyClass *) SpecialCase2
{
    return [MyClass myClassWithArg:2];
}

+ (MyClass *) myClassWithArg:(int)arg
{
    MyClass *instance = [[[MyClass alloc] initWithArg:arg] autorelease];

    return instance;
}

- (id) initWithArg:(int)arg
{
    self = [super init];
    if (nil != self) {
        self.arg = arg;
    }

    return self;
}

@end

The problem here (I think) is that the autorelease pool is flushed before the SpecialCaseN methods return to their callers. Hence, the ultimate caller of SpecialCaseN can't rely on the result having been retained. (I get "[MyClass copyWithZone:]: unrecognized selector sent to instance 0x100110250" on trying to assign the result of [MyClass SpecialCase1] to a property on another object.)

The reason for wanting the SpecialCaseN factory methods is that in my actual project, there are multiple parameters required to initialize the instance and I have a pre-defined list of "model" instances that I'd like to be able to create easily.

I'm sure there's a better approach than this.

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about iphone