Bruce Duncan
Bruce Duncan

Reputation: 269

alloc init inside methods

I have two methods in the same application

The first is in the Fraction Class

 -(Fraction *) divide: (Fraction *) f
 {
 Fraction *result = [[Fraction alloc] init];
 result.numerator = numerator * f.denominator
 [result reduce];
 return result;
 }

the second is in the calculator class

-(Fraction *) performOperation: (char) op
   {
 Fraction *result;
 switch (op) {
 case '+':
 result = [operand1 add: operand2];
 break;
 .
 .
 .
 .
 etc

break;
}
accumulator.numerator = result.numerator;
accumulator.denominator = result.denominator;
return accumulator;
}

Why does the first need to alloc and init the *result instance variable in the first method but not the second? Is it because it's calling another method [result reduce] or because its returning a value? or something else? The second method seems to simply instantiate a temp variable result of type Fraction without initializing or creating memory.

Thanks

Upvotes: 0

Views: 162

Answers (2)

Catfish_Man
Catfish_Man

Reputation: 41801

Your confusion stems from an inaccurate way of thinking about what's happening. It's clearer if you think about it this way:

Rather than "alloc init'ing the result variable", what you're doing is "alloc init'ing a Fraction object, and then assigning its address to the result variable".

The creation of the object is separate from assigning its address to the variable, and the object is not the same as the variable, the variable just refers to it.

So in the second case, you don't need to alloc init a Fraction because you're not trying to create a new empty Fraction, you're getting a pointer to a Fraction from somewhere else (the -add method in this case) and using it.

Also, your -divide method doesn't look right. You never set the denominator on your new Fraction.

Upvotes: 4

D_4_ni
D_4_ni

Reputation: 901

You already allocate and initialize the object inside the method and return a pointer to it. You then assign this pointer to a local variable - you don't need to allocate more memory for it.

Also, in case you don't use ARC, don't forget to either autorelease your result inside your -divide method, or release it in the -performOperation method after using it. Otherwise your app will leak memory.

Upvotes: 1

Related Questions