Allocating and Returning Objects from Methods

We noted that the add: method changes the value of the object that is receiving the message. Let’s create a new version of add: that instead makes a new fraction to store the result of the addition. In this case, we need to return the new Fraction to the message sender. Here is the definition for the new add: method:

-(Fraction *) add: (Fraction *) f{   // To add two fractions:   // a/b + c/d = ((a*d) + (b*c)) / (b * d)   // result will store the result of the addition   Fraction   *result = [[Fraction alloc] init];   result.numerator = numerator * f.denominator +                          denominator * f.numerator;   result.denominator = denominator * f.denominator; ...

Get Programming in Objective-C, Sixth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.