Search code examples
objective-cdefault-constructor

Declaration of constructor which allocates and initializes itself in Objective C


Possible Duplicate:
Class methods which create new instances

How would you declare a constructor in objective-c which would allow you to skip the [[class alloc] init] step during a declaration; Instead of saying for example Fraction* somefrac=[[Fraction alloc] init];, just say Fraction* somefrac and the constructor would do the rest.


Solution

  • This would instantiate the object and return it. Following naming conventions you would need to make it an autorelease'd object that gets returned.

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

    To use it

    Fraction *fraction = [Fraction fraction];
    

    this follows the same pattern as the apple provided classes e.g.

    NSArray *myArray = [NSArray array];