1

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.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2
+ (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.

1 Comment

Whoops, knew about that actually ;) Edited it now.
0

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.

3 Comments

What a silly comment. Of course more semantic implies meaningful, especially in comparison to new. Don't over think it. Look up the definition of semantics..."the study of meaning"
What do you dislike about my pattern? I know about custom initialisers like your initWithName: method, but I don't really see how your pattern would be different to mine.
Code is literature homie. Your code should read like sentences.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.