无法为NSNumber分配浮点数

sam*_*n01 2 iphone objective-c xcode4

我的根模型的m文件中有以下代码:

-(id)init {
    if(self == [super init]) {
        self.rPrices = [[NSMutableArray alloc]init];
        self.rPrices = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", nil];
}
    return self;
}

-(void)saveData:(NSMutableData *)data toFile:(NSString *)file {
float nR4;
nR4 = (some calculations ......)

[self.rPrices addObject:[[NSNumber alloc] numberWithFloat:nR4]];

}
Run Code Online (Sandbox Code Playgroud)

当我尝试添加对象时出现以下错误: 由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:' - [NSPlaceholderNumber numberWithFloat:]:发送到实例的无法识别的选择器

谢谢

omz*_*omz 8

numberWithFloat 是一个类方法,所以你必须像这样使用它:

[self.rPrices addObject:[NSNumber numberWithFloat:nR4]];
Run Code Online (Sandbox Code Playgroud)

但是这不起作用,因为你已经NSArray为你的rPrices属性分配了一个不可变的(不可变的意思是你无法修改它).你需要在NSMutableArray这里使用.