Reputation: 12517
Hi I have the following class called CalculatorOperations:
#import "CalculatorOperations.h"
@implementation CalculatorOperations
+(float)add:(float)numOne with:(float)numTwo{
return numOne + numTwo;
}
@end
I then try to call this class method as follows from within my Calculator class:
#import "Calculator.h"
#import "CalculatorOperations.h"
#import <Foundation/Foundation.h>
@implementation Calculator
+(float)add:(float)numOne to:(float)numTwo{
CalculatorOperations *calcOp = [CalculatorOperations alloc];
float answer = [calcOp add:numOne with:numTwo];
return answer;
}
@end
The problem is I keep getting a "incompatible types in initialisation" message when trying to assign the return value of a the add:with method to a variable (answer).
Why is this?
Upvotes: 0
Views: 1079
Reputation: 69459
The +
means that is is a Class method not an instance method, change the methods to -
to get it to be an instacne method.
#import "CalculatorOperations.h"
@implementation CalculatorOperations
- (float)add:(float)numOne with:(float)numTwo{
return numOne + numTwo;
}
@end
Also you need to init the class:
#import "Calculator.h"
#import "CalculatorOperations.h"
#import <Foundation/Foundation.h>
@implementation Calculator
+(float)add:(float)numOne to:(float)numTwo{
CalculatorOperations *calcOp = [[CalculatorOperations alloc] init];
float answer = [calcOp add:numOne with:numTwo];
return answer;
}
@end
Or change the call off the (float)add:(float)numOne with:(float)numTwo
method:
@implementation Calculator
+(float)add:(float)numOne to:(float)numTwo{
float answer = [CalculatorOperations add:numOne with:numTwo];
return answer;
}
@end
Damm I need to learn to type faster.
Upvotes: 1
Reputation: 1325
You shouldn't be calling a class method (the +
indicates class method) on an instance of the class. In addition, you aren't init
ing the class as required for an instance of that class.
Try this:
@implementation Calculator
+(float)add:(float)numOne to:(float)numTwo{
return [CalculatorOperations add:numOne with:numTwo];
}
@end
Upvotes: 2
Reputation: 22334
You need....
CalculatorOperations *calcOp = [[CalculatorOperations alloc] init];
Plus your method is a class method (hence the +)...
float value = [CalculatorOperations add:1.0 with:2.0];
Upvotes: 0