Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
May 26, 2018, 02:19:22 PM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
   Home   Help Search Login Register Chat  
Pages: [1]   Go Down
Author Topic: Does this look good - Exercise 7.2 (+Question)  (Read 1641 times)
Posts: 49

« on: February 21, 2012, 05:52:27 PM »

I ended up with this code:
Code: (Objective-C)
-(void) print: (BOOL) redu
    Fraction *tempo = [[Fraction alloc] init];
    [tempo setTo: numerator over: denominator];
    int u = numerator;
    int v = denominator;
    int temp;
    while (v != 0)
        temp = u % v;
        u = v;
        v = temp;
    if (u != 1)
        redu = YES;
        redu = NO;
    if (redu)
        tempo.numerator /= u;
        tempo.denominator /= u;
    else if (!tempo.numerator)
        NSLog (@"0 (zero)");
    else if (tempo.denominator == 1)
        NSLog (@"%i", tempo.numerator);
        NSLog (@"%i/%i", numerator, denominator);
What do you think? I included part of the reduce method here since I think we should check first whether the fraction needs to be reduced rather than take the fraction through the reduce method anyways.

Also, I haven't actually realized that we can use other methods inside a method. Is it true since I don't remember any mentions in the book.

Thank you.
Posts: 8

« Reply #1 on: February 29, 2012, 11:28:12 PM »

Yes, methods can be called from within other methods.  To call a method from the same object, use the self declaration:
Code: (Objective-C)
-(void) add: (Fraction *) f{
    numerator = numerator * f.denominator + f.numerator * denominator;
    denominator *= f.denominator;
    [self reduce];
You can also call methods to apply to other objects, like so:
Code: (Objective-C)
-(Fraction *) add: (Fraction *) f{
    Fraction *result = [Fraction new];
    result.numerator = numerator * f.denominator + f.numerator * denominator;
    result.denominator = denominator * f.denominator;
    [result reduce];
    return result;

More experienced members may have more detailed answers or better examples.

Pages: [1]   Go Up
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents ゥ 2009 All rights reserved.