获取无效操作数到二进制表达式('id'和'id')和错误的计算值

时间:2014-05-21 18:40:51

标签: ios objective-c

获取此错误"无效操作数到二进制表达式(' id'和' id')"当我尝试使用存储在数组中的值进行一些基本数学运算时。注释掉的代码有效,但出于某种原因给出了错误的值。

@implementation OMOGradesViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    // Call init method implemented by the superclass
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if(self){
        // Create array of grades
        self.grades = @[@80, @70, @60, @50, @40];
        // self.grades = @[@"80", @"70", @"60", @"50", @"40"];

}

    // Return the address to the new object
    return self;
}

- (IBAction)calculateAvg:(id)sender
{

    for(NSArray *a in self.grades)
        NSLog(@"%@", a);

    int *avg = ([self.grades objectAtIndex:0] + [self.grades objectAtIndex:1]);

    /*int avg = ((int)self.grades[0] + (int)self.grades[1] + (int)self.grades[2]
    + (int)self.grades[3] + (int)self.grades[4])/5;

    NSString *strFromInt = [NSString stringWithFormat:@"%d",avg];

    self.averageLabel.text = strFromInt;
    NSLog(@"%@", strFromInt);*/


}

@end

1 个答案:

答案 0 :(得分:5)

这里有很多错误。这样:

int *avg = ([self.grades objectAtIndex:0] + [self.grades objectAtIndex:1]);

应该是:

int avg = [self.grades[0] intValue] + [self.grades[1] intValue];

您无法直接添加NSNumber个对象。您需要获取int值(使用intValue)。

而您的avg无法成为int指针,只是一个普通的int

我还用现代数组访问语法替换了对objectAtIndex:的调用。