简体   繁体   English

Objective C - 使用多个参数实例化对象和调用方法

[英]Objective C - Instantiating Objects and Calling Methods with Multiple Parameters

Hi I have the following class called CalculatorOperations:嗨,我有以下 class 称为 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:然后我尝试在我的计算器 class 中调用此 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).问题是在尝试将 add:with 方法的返回值分配给变量(答案)时,我不断收到“初始化中的类型不兼容”消息。

Why is this?为什么是这样?

You shouldn't be calling a class method (the + indicates class method) on an instance of the class.您不应该在 class 的实例上调用 class 方法( +表示 class 方法)。 In addition, you aren't init ing the class as required for an instance of that class.此外,您没有按照 class 实例的要求init class。

Try this:尝试这个:

@implementation Calculator

+(float)add:(float)numOne to:(float)numTwo{
    return [CalculatorOperations add:numOne with:numTwo];
}

@end

The + means that is is a Class method not an instance method, change the methods to - to get it to be an instacne method. +表示 Class 方法不是实例方法,将方法更改为-使其成为实例方法。

 #import "CalculatorOperations.h"
 @implementation CalculatorOperations

- (float)add:(float)numOne with:(float)numTwo{
    return numOne + numTwo;
}
@end

Also you need to init the class:您还需要初始化 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:或者(float)add:(float)numOne with:(float)numTwo的调用:

@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.该死的,我需要学会更快地打字。

You need....你需要....

CalculatorOperations *calcOp = [[CalculatorOperations alloc] init];

Plus your method is a class method (hence the +)...另外,您的方法是 class 方法(因此是+)...

float value = [CalculatorOperations add:1.0 with:2.0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM