0

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.

Community
  • 1
  • 1
Iowa15
  • 3,027
  • 6
  • 28
  • 35

2 Answers2

3

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];
Paul.s
  • 38,494
  • 5
  • 70
  • 88
0
+(Fraction *) fraction
{
    return [[[Fraction alloc] init] autorelease];
}

and then you can use

Fraction *frac = [Fraction fraction];

This style is used a lot in objective c

grahamparks
  • 16,130
  • 5
  • 49
  • 43
Daniel
  • 30,896
  • 18
  • 85
  • 139
  • What happens if you want to subclass `Fraction`? – Paul.s Nov 20 '11 at 18:51
  • @Paul.s: then you have to provide such a class method yourself. its not logical to call `[Derived base]` but rather `[Derived derived]` – Daniel Nov 20 '11 at 18:53
  • That doesn't sounds very DRY to me. As you would then be writing the same method again? – Paul.s Nov 20 '11 at 18:57
  • @Paul.s: I know its a bit tedious, but I rather get derived object through derived function rather than base function. if anything, it would help if objective c would allow some kind of `@synthesize` syntax for converting `init`s to this. – Daniel Nov 20 '11 at 19:00
  • 2
    Indeed it would. One suggestion to keep it a little DRY'er. Define it as I have in my answer then at least you could have `- (id)derived; { return [self fraction]; }` then you get all the normal benefits of changes bubbling up the inheritance tree – Paul.s Nov 20 '11 at 19:02