Tim Vermeulen
Tim Vermeulen

Reputation: 12562

Writing an abstract class custom initializer method

In an abstract class, a custom init method looks like this:

- (id)init
{
    self = [super init];

    if (self)
    {
        //do some initialisations
    }

    return self;
}

This would work perfectly fine when working with abstract classes: no problems at all. However, when creating objects, I prefer Class *object = [Class new]; over Class *object = [[Class alloc]init];. The problem with such a method in my abstract class, is that this doesn't work:

+ (id)new
{
    id object = [super new];

    if (object)
    {
        //do some initialisations
    }

    return object;
}

When trying to access properties of the object, Xcode will bring up an error, saying the corresponding property is not found on object of type '__strong id'. I'm guessing that's because the compiler has no idea what properties my object has, as it's just been created.

Is there any way to get around this limitation? If there's not, I'll just use the init method as it works just fine, but I was just curious about this.

Upvotes: 1

Views: 147

Answers (3)

hisdrewness
hisdrewness

Reputation: 7651

I would not suggest the pattern you're using. It is much more semantic to create custom factory method initializer methods:

- (id) init
{
   // init code
}

- (id) initWithName:(NSString *)name
{
   // init code
}

+ (id) personWithName:(NSString *)name
{
    // add autorelease on non-ARC
    return [[super alloc] initWithName:name];
}

Person *person = [Person personWithName:@"Steve Jobs"];

Notice that it's a class method.

Upvotes: 0

Matt Wilding
Matt Wilding

Reputation: 20163

You don't need to override new. According to the documentation, new...

Allocates a new instance of the receiving class, sends it an init message, and returns the initialized object.

So you only ever override init to perform your initialization. You're then free to create instances via alloc/init or new, depending on your taste.

Upvotes: 3

Analog File
Analog File

Reputation: 5316

+ (id)new
{
    return [[self alloc] init;
}

Note the + instead of - as this is a class method.

Except you do not need to write that as new is already implemented in NSObject.

Upvotes: 2

Related Questions