質問

I've tried to convert the UITextfield Value Into a float first then convert it to an NSNumber but that doesn't seem to work as seen below.

       float carb = [self.carbGrams.text floatValue];
       NSLog(@"%.2f", carb);
       nCarbGrams = carb;

In the last line I get this error message:

Assigning to 'NSNumber *__strong' from incompatible type 'float'

I've then just tried assigning carb as an NSNumber by doing this

      NSNumber *carb = [self.carbGrams.text floatValue];
      NSLog(@"%.2f", carb);
      nCarbGrams = carb;

But I get this error message instead :

Initializing 'NSNumber *__strong' with an expression of incompatible type 'float'

As I've read I though NSNumber could accept any type of numeric value but I seem to be incorrect, can someone please evaluate the problem?

役に立ちましたか?

解決 2

You need to create an object of typ NSNumber from the float. As such

float carb = [self.carbGrams.text floatValue];
NSNumber *nCarb = [NSNumber numberWithFloat: carb];

or why not use the fancy (new) literal syntax

NSNumber *nCarb = @([self.carbGrams.text floatValue]);

他のヒント

You can use Objective-C literal syntax:

NSNumber *carb = @([self.carbGrams.text floatValue]);

Try this:

NSNumber *carb = [NSNumber numberWithFloat:[self.carbGrams.text floatValue]];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top