CloudDweller
CloudDweller

Reputation: 33

Setting Objective-C instance variable values

I have the following code:

@implementation Fraction   
{  
      int   numerator;  
      int   denominator;  
}  

    -(void) setNumerator: (int) n   
{  
    numerator = n;   
}  
    -(void) setDenominator: (int) d   
{  
    denominator = d;   
}
@end

I was wondering why you have to have both "n" and "numerator" for the numerator? For example why can't you just set

-(void) setNumerator: (int) numerator

as apposed to:

-(void) setNumerator: (int) n
     numerator = n;
}

Sorry if this is such a basic question but I'm starting from the beginning with no programming experience.

Upvotes: 2

Views: 1442

Answers (2)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81694

The setNumerator method is used to tell a Fraction object what value it should hold in the variable named numerator. As in "Here, Mr. Fraction, please use the value n for your numerator." In the implementation of this method, the code has to deal with two different concepts: the parameter variable n containing the new value, and the instance variable numerator which must be changed to the value in n; hence the need for two different names. The line

numerator = n;

literally means "copy the number in n into the variable numerator."

Remember, there are two halves to the transaction. Say I'm a Fraction object, and you want me to set my numerator to 4. You say "Set your numerator to 4, or setNumerator(4)", which is fine, because you're human, and you get to choose whatever number you want.

But as a lowly Objective-C object, all my code was written some time in the past; it was written before the value 4 was even a twinkle in your eye. So the code for setNumerator() has to be generic; it has to be written to say "set numerator to whatever value the human wants -- call it n". Remember, my actual variable numerator is hidden from you; all you can do is call my method, and it's up to me to set the variable.

That's why the method must be written to use an abstract name -- n -- for the value, since when the method is written, the value is unknown.

Upvotes: 2

Paul Sasik
Paul Sasik

Reputation: 81489

I think the concept you may be looking is called properties. Take a look here and here and here. Properties will allow you to set member values without having to name a parameter or call a method. You simply assign a value to the property.

With a function call you have to name the parameter that you are passing into the function so that you can assign it to the class member.

Upvotes: 0

Related Questions