Just the changed parts of the Fraction class:
@implementation Fraction (MathOps)
-(Fraction *) add: (Fraction *) f
{
// To add two fractions
// a/b + c/d = ((a*d) + (b*c)) / (b*d)
// result will store the results of the addition
Fraction *result = [[[Fraction alloc] init] autorelease];
int resultNum, resultDenom;
resultNum = numerator * f.denominator + denominator * f.numerator;
resultDenom = denominator * f.denominator;
[result setTo: resultNum over: resultDenom];
[result reduce];
return result;
}
-(Fraction *) subtract: (Fraction *) f
{
Fraction *result = [[[Fraction alloc] init] autorelease];
int resultNum, resultDenom;
resultNum = numerator * f.denominator - denominator * f.numerator;
resultDenom = denominator * f.denominator;
[result setTo: resultNum over: resultDenom];
[result reduce];
return result;
}
-(Fraction *) multiply: (Fraction *) f
{
Fraction *result = [[[Fraction alloc] init] autorelease];
int resultNum, resultDenom;
resultNum = numerator * f.numerator;
resultDenom = denominator * f.denominator;
[result setTo: resultNum over: resultDenom];
[result reduce];
return result;
}
-(Fraction *) divide: (Fraction *) f
{
Fraction *result = [[[Fraction alloc] init] autorelease];
int resultNum, resultDenom;
resultNum = numerator * f.denominator;
resultDenom = denominator * f.numerator;
[result setTo: resultNum over: resultDenom];
[result reduce];
return result;
}
@end
#import <Foundation/Foundation.h>
#import "Fraction.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *fractionA = [[[Fraction alloc] init] autorelease];
Fraction *fractionB = [[[Fraction alloc] init] autorelease];
[fractionA setTo: 3 over: 4];
[fractionB setTo: 1 over: 8];
[[fractionA add: fractionB] print];
[pool drain];
return 0;
}
7/8
In main, both fractionA and fractionB were added to the autorelease pool when created, and will be destroyed when the autorelease pool drains at the end of main. No need to release them explicitly.
In the four methods of Fraction (MathOps), result was added to the autorelease pool when it was created and is returned when the method is invoked, for example: [fractionA add: fractionB]. As this returned Fraction object was marked for autorelease before being returned, it too will be destroyed when the autorelease pool drains at the end of main. Again, no need to release it explicitly.
Indeed, explicitly releasing either fractionA and fractionB, or any of the result objects in Fraction (MathOps) would cause the program to crash, as they would no longer be around for destruction by the autorelease pool.