Line for swimming in the lens c

I have a parser that returns some string value that I would like to use as a parameter to initialize an instance of the class.

I have a method requesting two values ​​of NSString and float, but I cannot convert the string to float, here is my code:

 NSString *from = [[NSString alloc] initWithString:@"EUR"];
    NSString *to = [[NSString alloc] initWithString:[attributeDict objectForKey:@"currency"]];
    NSNumber *rate = [[NSNumber alloc] initWithFloat:[[attributeDict objectForKey:@"rate"] doubleValue]];


   currency = [[Currency init] alloc];
   [currency addCurrencyWithFrom:from andTo:to andRate:rate];

in .h

- (id) addCurrencyWithFrom: (NSString *) from_ andTo:(NSString *) to_ andRate:(float *) float_;
+5
source share
3 answers

No, no, no, no, no, no, no, no, no.

Use NSNumberFormatter. That is why it exists. -floatValueand -doubleValueare just quick and temporary fixes, but they fail. For instance:

NSLog(@"%f", [@"123" floatValue]); //logs 123.0000
NSLog(@"%f", [@"abc" floatValue]); //logs 0.0000
NSLog(@"%f", [@"0" floatValue]);   //logs 0.0000
NSLog(@"%f", [@"42" floatValue]);  //logs 42.0000
NSLog(@"%f", [@"42x" floatValue]); //logs 42.0000

-floatValue (@"0") (@"abc").

NSNumberFormatter, , nil, , NSNumber, . , , , . -floatValue .

. : NSString NSNumber

+18
float f = [yourStringObject floatValue];
+7

Try:

double f = [from_ doubleValue];
double t = [to_ doubleValue];

, NSNumber * float .

+1

All Articles