K17 K17 - 1 year ago 80
iOS Question

Converting float to NSNumber

I am missing something basic, here. Must have forgotten it. But basically, I have the following code the purpose take an NSNumber, convert it to float, multiply it by 2 and return the result to an NSNumber. I get an error on the last step, and am stumped. What should I do there.

NSNumber *testNSNumber = [[[NSNumber alloc] initWithFloat:200.0f] autorelease];
float myfloatvalue = [testNSNumber floatValue] * -2;
NSLog(@" Test float value %1.2f \n\n",myfloatvalue);
[testNSNumber floatValue:myfloatvalue]; // error here is floatValue is not found

Answer Source

The method floatValue of NSNumber does not take parameters. If you would like to set a new float number, you need to re-assign testNSNumber, because NSNumber does not have a mutable counterpart:

testNSNumber = @(myfloatvalue); // The new syntax


testNSNumber = [NSNumber numberWithFloat: myfloatvalue]; // The old syntax