user559142
user559142

Reputation: 12517

Objective C - Instantiating Objects and Calling Methods with Multiple Parameters

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

Answers (3)

rckoenes
rckoenes

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

pkananen
pkananen

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 initing 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

Simon Lee
Simon Lee

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

Related Questions