saman01
saman01

Reputation: 21

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

Upvotes: 2

Views: 4902

Answers (4)

Mat
Mat

Reputation: 7633

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

}

Upvotes: 0

Michaël
Michaël

Reputation: 6734

[NSNumber  numberWithFloat:nR4];

or

[[NSNumber alloc] initWithFloat:nR4];

Upvotes: 1

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31722

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]];

Upvotes: 2

omz
omz

Reputation: 53551

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.

Upvotes: 8

Related Questions