Search code examples
objective-cmethodsfractions

Objective-C method pointer send message


I am new to obj-c programming, I read Kochan's book.

here is code from book

-(void) add:(Fraction *) f 
{
  numerator = numerator *f.denominator + denominator * f.numerator
  denominator = numerator * f.denominator

}

I know the 'f' is point to Fraction, but I dont understand inside method that why using f.numerator or f.denominator.

Is anyone can explain it for me? my first language is not english. so please make it simple.

Edit :well,in math we using (a/b)+(c/d) =(ad+bc)/(bd), I know this formula. I just dont get it that why after asterisk why put f dot something.I want to know f point to where.

*EDIT*2

I still have litte problem about words in Parentheses which "(Fraction *)f"

In the book says "This says that argument to the add:method is a reference to an object from the Fraction class"

does the Fraction in that parentheses is point to Fraction class ? or the word "f" is point to Fraction class?

I dont understand this sentence. Can you give me more detail about that?

EDIT 3

inside add method. why using the just one f dot something? I mean looks this

numerator = numerator *f.denominator + denominator * f.numerator

why we can not write code like this part.

numerator = f.numerator *f.denominator + f.denominator * f.numerator

I dont understand this part.

Thanks.


Solution

  • It appears to be a public property on the Fraction class. f is an instance of the Fraction class. numerator and denominator are public properties in the Fraction class. The dot notation is equivalent to [f numerator].

    EDIT

    Here is the rewritten code using the alternate message sending syntax.

    -(void) add:(Fraction *) f 
    {
      denominator = numerator * [f denominator];
      numerator = numerator * [f denominator] + denominator * [f numerator];
    }
    

    EDIT 2. The Fraction class header probably looks something like this.

    class Fraction : NSObject
    
    // methods
    // ...
    
    @property (nonatomic, strong) int numerator;
    @property (nonatomic, strong) int denominator;
    
    // other properties
    // ...
    
    end