Let’s dive right into this lesson by extending our Fraction class and covering some miscellaneous OOP concepts.

## Implementing New Methods

The last post, which described methods in detail, mentioned a method called setNumerator:overDenominator:. As you might have guessed, we are going to implement this functionality into our Fraction class, and see how we use a method with multiple arguments.

Open up Fraction.h from the project we’ve been working on; alternatively, you can download the files by clicking here. Add the following line to the list of methods (it doesn’t matter exactly where you place it, as long as it’s between the @propertys and the final @end):

`- (void)setNumerator:(NSInteger)num overDenominator:(NSInteger)denom;`

In Fraction.m, add the following implementation for the method:

1. ```- (void)setNumerator:(NSInteger)num overDenominator:(NSInteger)denom { ```
2. ```    self.numerator = num; ```
3. ```    self.denominator = denom; ```
4. `}`

Note that the names of the arguments in this method are num and denom are not the same as the instance variables numerator and denominator. This is because every instance method has access to the class’s instance variables (remember that a class is just an object that gets created at runtime—hypothetically, it would be weird if a car did not have access to its current speed (speedometer) or fuel level). Because of this, if your argument names are the same name as an instance variable, and you try to reference the argument or the instance variable, the compiler will get confused. At best, you’ll have runtime issues; at worst, the program will refuse to compile.

Update the main function (FractionDemo.m) to have the following code:

1. ```#import "Fraction.h" ```
2. ```#import <Foundation/Foundation.h> ```
3. ` `
4. ```int main (int argc, const char * argv[]) { ```
5. ```    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; ```
6. ` `
7. ```    Fraction *myFraction = [[Fraction alloc] init]; ```
8. ` `
9. ```    // Set myFraction to value of 2/5 ```
10. ```    /* [myFraction setNumerator: 2]; ```
11. ```    [myFraction setDenominator: 5]; */ ```
12. ` `
13. ```    /* myFraction.numerator = 2; ```
14. ```    myFraction.denominator = 5; */ ```
15. ` `
16. ```    [myFraction setNumerator:2 overDenominator:5]; ```
17. ` `
18. ```    // Display the value of myFraction ```
19. ```    NSLog(@"myFraction has a value of: "); ```
20. ```    [myFraction display]; ```
21. ` `
22. ```    [myFraction release];   ```
23. ```    [pool drain]; ```
24. ```    return 0; ```
25. `}`

Just note that the main() function is where any program starts executing. Here, we are placing our actual program (where something is done) inside the main() routine; when we begin building iPhone apps, we will almost never modify main().

Build and run your program. The output should be exactly as expected:

1. ``` myFraction has a value of: ```
2. `2/5`

## Fraction Operations

Here, we will implement an instance method to add two fractions. As an exercise to you, try to implement subtraction, multiplication, and division! The code will be available for download at the end of this post, but try to do it on your own.

(a/b) + (c/d) = (ad + bc)/(bd)

Our method looks like this:

`- (void)add:(Fraction *)newFraction;`

Note that we are passing in another Fraction object (technically, the asterisk symbolizes that we are passing in a pointer, or reference to a Fraction object). Also note that although we are only passing in one value to be added, the other (implied) value in the addition is the instance of Fraction that we’re calling this method on. Every method has access to its own instance variables, and as we’ll discover later in this post, every method can reference self.

The implementation of the method is as follows:

1. ```- (void)add:(Fraction *)newFraction { ```
2. ```    // a/b + c/d = ((a * d) + (b * c)) / (b * d) ```
3. ```    self.numerator = self.numerator * newFraction.denominator + self.denominator * newFraction.numerator; ```
4. ```    self.denominator = self.denominator * newFraction.denominator; ```
5. `}`

The parentheses were not strictly necessary, but made it easier to read and understand.

Let’s test this new method:

1. ```#import "Fraction.h" ```
2. ```#import <Foundation/Foundation.h> ```
3. ` `
4. ```int main (int argc, const char * argv[]) { ```
5. ```    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; ```
6. ` `
7. ```    Fraction *aFraction = [[Fraction alloc] init]; ```
8. ```    Fraction *bFraction = [[Fraction alloc] init]; ```
9. ` `
10. ```    [aFraction setNumerator:1 overDenominator:2]; ```
11. ```    [bFraction setNumerator:1 overDenominator:3]; ```
12. ` `
13. ```    [aFraction display]; NSLog(@" + "); [bFraction display]; NSLog(@" = "); ```
14. ```    [aFraction add:bFraction]; ```
15. ```    [aFraction display]; ```
16. ` `
17. ```    [aFraction release];     ```
18. ```    [bFraction release]; ```
19. ```    [pool drain]; ```
20. ```    return 0; ```
21. `}`

The result:

1. ```1/2 ```
2. ```+ ```
3. ```1/3 ```
4. ```= ```
5. `5/6`

This is exactly correct.

## Variable Scope

If we try our program with different numbers (say, 2/4 and 1/3, which do happen to have the same values), we get a result of 10/12. Our current add method simply adds, without reducing the value. Let’s implement a method that reduces any Fraction:

1. ```- (void)reduce { ```
2. ```    int u = self.numerator; ```
3. ```    int v = self.denominator; ```
4. ```    int temp = 0; ```
5. ` `
6. ```    // Euclid's procedure to find GCD (Greatest Common Denominator) ```
7. ```    // Don't worry about how this works, exactly. ```
8. ` `
9. ```    while (v != 0) { ```
10. ```        temp = u % v; ```
11. ```        u = v; ```
12. ```        v = temp; ```
13. ```    } ```
14. ` `
15. ```    self.numerator /= u; ```
16. ```    self.denominator /= u; ```
17. `}`

This method declares three integer values called u, v, and temp. These are local variables—they only exist during the execution of the reduce method, they can only be accessed from the same method, and get cleared once the method is done. In more formal parlance, these variables’ scope is limited to this method. These variables must be initialized (given a value) before they are used; every time the method is invoked (called), these values are set to the default initial values.

Incidentally, this scope also applies to variables defined within loops and if() blocks—those variables would only be accessible within the same block. As a general rule of thumb, a variable is always and only accessible in the same block as the declaration itself. A block is delineated by curly braces ({ }).

The same scope is applied to method arguments. The arguments contain a copy of the value that you pass in, not the original. For primitive types, such as ints or floats, this means that you cannot modify the original value that you passed in, only the copy. Whenever you pass in an object (more precisely, an object pointer—more on that in the next Extension), you can, in fact, modify the original object, because a copy is made of the memory address, not of the object itself. Don’t worry if that last line was confusing; it’ll be quickly cleared up.

Let’s test our reduce method:

1. ```#import "Fraction.h" ```
2. ```#import <Foundation/Foundation.h> ```
3. ` `
4. ```int main (int argc, const char * argv[]) { ```
5. ```    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; ```
6. ` `
7. ```    Fraction *aFraction = [[Fraction alloc] init]; ```
8. ```    Fraction *bFraction = [[Fraction alloc] init]; ```
9. ` `
10. ```    [aFraction setNumerator:2 overDenominator:4]; ```
11. ```    [bFraction setNumerator:1 overDenominator:3]; ```
12. ` `
13. ```    [aFraction display]; NSLog(@" + "); [bFraction display]; NSLog(@" = "); ```
14. ```    [aFraction add:bFraction]; ```
15. ```    [aFraction reduce]; ```
16. ```    [aFraction display]; ```
17. ` `
18. ```    [aFraction release];     ```
19. ```    [bFraction release]; ```
20. ```    [pool drain]; ```
21. ```    return 0; ```
22. `}`

The resulting fraction is the expected 5/6, not 10/12.

## Static variables

A static variable is one that retains its value through multiple method calls to the same variable. Unlike a regular variable declared in a method, which gets cleared after the method is finished, a static variable does not get cleared. A static variable is automatically set to 0 at creation:

`static int counter;`

You do not need to set the variable to 0; that is already done.

Although static variables retain their value through successive method calls, they are still only accessible in that method. Some static variables are placed outside any method, sometimes even before the @implementation line, so that they can accessed in any method.

If a variable is a local static variable, it could be used anytime that method in which it was defined is called. If it were an instance variable, it would be able to be changed from any method. This makes it very similar to a static variable outside any method. The difference at this point is a matter of conventions. If you need to keep track of a value which does not necessary seem to “belong” to an object (for instance, the number of potholes a Car object has metaphorically gone over probably won’t be an instance variable of Car (because it is not a property of Cars), but could still be a static variable).

## self

The self keyword is used to access the receiver of the method—the same object that sent the message in the first place. For instance, in our add: method, we could have reduced the value directly in the method:

1. ```- (void)add:(Fraction *)newFraction { ```
2. ```    // a/b + c/d = ((a * d) + (b * c)) / (b * d) ```
3. ```    self.numerator = self.numerator * newFraction.denominator + self.denominator * newFraction.numerator; ```
4. ```    self.denominator = self.denominator * newFraction.denominator; ```
5. ` `
6. ```    [self reduce]; ```
7. `}`

This invokes the reduce method on the same object that sent the add: method (in this case, aFraction). We can remove the reduce line from the main() routine.

## Class Methods

We can also write a class method that takes two Fractions, adds them, and returns a new Fraction. Look through the following code, and see if it makes sense.

Fraction.h

1. `+ (Fraction *)addFraction:(Fraction *)frac1 toFraction:(Fraction *)frac2;`

Fraction.m

1. ```+ (Fraction *)addFraction:(Fraction *)frac1 toFraction:(Fraction *)frac2 { ```
2. ```    Fraction *result = [[[Fraction alloc] init] autorelease];   // Store result of addition ```
3. ```                                                                // Autorelease is memory management— ```
4. ```                                                                // Don't worry about it now. ```
5. ` `
6. ```    NSInteger resultNum = frac1.numerator * frac2.denominator + frac1.denominator * frac2.numerator; ```
7. ```    NSInteger resultDenom = frac1.denominator * frac2.denominator; ```
8. ` `
9. ```    [result setNumerator:resultNum overDenominator:resultDenom]; ```
10. ```    [result reduce]; ```
11. ` `
12. ```    return result; ```
13. `}`

FractionDemo.m

1. ```// Reset fractions ```
2. ```    [aFraction setNumerator:2 overDenominator:4]; ```
3. ```    [bFraction setNumerator:1 overDenominator:3]; ```
4. ` `
5. ```    NSLog(@"Using class method:"); ```
6. ```    Fraction *classAddition = [Fraction addFraction:aFraction toFraction:bFraction]; ```
7. `    [classAddition display];`

The result is the same: 5/6.