Coding help

Discussion in 'iOS Development' started by thund3r, Aug 17, 2010.

  1. thund3r

    thund3r Member

    Joined:
    Feb 8, 2009
    Messages:
    100
    Likes Received:
    0
    Device:
    iPad
    -(Fraction *) add: (Fraction *) f;

    I am currently reading a book called "Programming in Objective-c 2.0".
    While i was reading the book, i came across this line. It seems like it is a method name but i do not understand what it exactly does. Can someone teach me what this does?

    Implementation section:

    -(Fraction *) add: (Fraction *) f;
    {
    Fraction *result = [[Fraction alloc] init];

    result.numerator = ( numerator * f.denominator)
    + ( denominator * f.numerator);
    result.denominator= denominator *= f.denominator;

    [result reduce];
    return result;
    }
  2. lauNchD

    lauNchD Well-Known Member

    Joined:
    Jan 27, 2008
    Messages:
    1,844
    Likes Received:
    261
    Device:
    iPhone 5 (Black)
    First of all, please use [NOPARSE][OBJC] /* code */ [/OBJC][/NOPARSE] tags next time. That makes the code much more readable

    Please Register or Log in to view images



    To answer your question, yes, you're looking at a method implementation. What it does is create a new Fraction object containing the sum of the reciever (the Fraction that this method is being called on) and some other Fraction.

    The actual fraction adding part is simple arithmetics.

    2/3 + 1/4 = (2*4 + 3*1)/3*4 = 11/12

    1/3 + 1/6 = (1*6 + 3*1)/3*6 = 9/18
    9/18 reduced = 1/2

    For more information, I recommend you visit this site

    Please Register or Log in to view images



    On a side note, I'm not sure this method is a very good example for Cocoa naming and memory management conventions. It should probably be called something like fractionByAddingFraction: and the resulting object should be autoreleased.
  3. Axis

    Axis Super Moderator Staff Member

    Joined:
    Dec 2, 2007
    Messages:
    6,288
    Likes Received:
    133
    Device:
    iPhone 4S (White)
    ^ Agreed. The instance method name 'add' implies that the receiver is being modified.
  4. thund3r

    thund3r Member

    Joined:
    Feb 8, 2009
    Messages:
    100
    Likes Received:
    0
    Device:
    iPad
    What does the "f." do? eg. f.numerator
  5. MountainDew

    MountainDew New Member

    Joined:
    Feb 23, 2008
    Messages:
    194
    Likes Received:
    1
    Device:
    iPod touch
  6. lauNchD

    lauNchD Well-Known Member

    Joined:
    Jan 27, 2008
    Messages:
    1,844
    Likes Received:
    261
    Device:
    iPhone 5 (Black)
    f is just the variable name of the method argument
    "in English": it represents the fraction that gets added to self / "your" fraction

    As MountainDew said, the ".numerator" means you're accessing the fraction's numerator property using the Dot Syntax.

Share This Page