Can not assign a float to NSNumber
I have the following code in the m file of my root model:
-(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]];
}
I get the following error when I try to add the object: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSPlaceholderNumber numberWithFloat:]: unrecognized selector sent to instance
Thanks
numberWithFloat
is a class method, so you must use it like this:
[self.rPrices addObject:[NSNumber numberWithFloat:nR4]];
This won't work however, because you've assigned an immutable NSArray
to your rPrices
property (immutable meaning that you can't modify it). You need to use NSMutableArray
here.
It seems, you are calling an class method
on the object.
Try with changing the statement as below.
[self.rPrices addObject:[NSNumber numberWithFloat:nR4]];
As also try with changing the way you construct your array.'
self.rPrices = [[NSMutableArray alloc] initWithCapacity:2];
[self.rPrices addObjectsFromArray:[NSArray arrayWithObjects:@"1", @"2", @"3", @"4", nil]];
[NSNumber numberWithFloat:nR4];
or
[[NSNumber alloc] initWithFloat:nR4];
You don't need to initialize the array twice:
-(id)init {
self = [super init];
if (self != nil) {
//self.rPrices = [[NSMutableArray alloc]init]; //this does not need
rPrices = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", @"4", nil];
}
return self;
}
-(void)saveData:(NSMutableData *)data toFile:(NSString *)file {
float nR4;
nR4 = (some calculations ......)
[self.rPrices addObject:[NSNumber numberWithFloat:nR4]];//This return an autoreleased OBJ so you don't need to call alloc
}
精彩评论