How do I pass first_number and second_number to the +add_function?
I am currently getting math undeclared.
Additionally, I have placed the pound include math_class in the -addButtonClicked: IBAction.
Also, I realize that I can simply add the two numbers in the IBAction, but for learning purposes I would like to pass them to my math_class.
-(IBAction)addButtonClicked
{
double total;
double first_number = [firstNumberField.text doubleValue];
double second_number = [secondNumberField.text doubleValue];
total = [math_class.add_function number_one:first_number number_two:second_number];
answerField.text = [NSString stringWithFormat:@"%.2f", total];
[answerField setHidden:NO];
}
@interface math_class : NSObject
+ (double) add_function: (double) number_one: (double) number_two;
@end
@implementation math_class
+(double) add_function: (double) number_one: (double) number_two
{
double total;
total = number_one + number_two;
return total;
}
@end
There are several problems with the code you posted.
First of all, the convention in Cocoa Touch is that class names use camel-case and start with a capital letter:
MathClass, notmath_class. Method names use camel-case and each keyword starts with a lower-case letter. If you stick to the naming convention, it will be easier for other people to understand your code, so it will be easier for you to get help when you have a problem.Now, in your
math_classclass, you have declared a method like this:But you’ve put in spaces and left out spaces in an unusual way. The usual way to write it, keeping exactly the same method name, looks like this:
The name of this method is
add_function::, notadd_function number_one:number_two:(which is what you used to try to call it).This method name has two keywords. The first keyword is
add_function:and takes adoubleargument namednumber_one. The second keyword is just:and takes adoubleargument namednumber_two.You could call this method like this:
However, using a method name with a keyword of just
:is almost always very bad style.There are lots of ways to write your class in good style. Here’s one way:
When a method is used primarily for its return value, and not for side effects, we name it after the thing it returns. So I called it
sumWithNumber:number:because it returns a sum.The method name has two keywords. The first keyword is
sumWithNumber:and takes adoubleargument namedfirstNumber. The second keyword isnumber:and takes adoubleargument namedsecondNumber. You can call it like this: