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

Mar*_*cus 0 objective-c ios

当我尝试使用存储在数组中的值进行一些基本数学运算时,将此错误"无效操作数转换为二进制表达式('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
Run Code Online (Sandbox Code Playgroud)

rma*_*ddy 5

这里有很多不妥之处.这个:

int *avg = ([self.grades objectAtIndex:0] + [self.grades objectAtIndex:1]);
Run Code Online (Sandbox Code Playgroud)

应该:

int avg = [self.grades[0] intValue] + [self.grades[1] intValue];
Run Code Online (Sandbox Code Playgroud)

您无法NSNumber直接添加对象.你需要获得他们的int价值(使用intValue).

avg不能成为一个int指针,只是一个普通的旧指针int.

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