views:

532

answers:

2

I have a UITextField called txtDiscount It has a value in it: txtDiscount.text == 2.3 //for example

I've tried:

float test = (NSNumber *)txtDiscount.text;

And it compiles, but at runtime breaks down.

Unacceptable type of value for attribute: property = ..."; desired type = NSNumber; given type = NSCFString; value = .

How can I cast the value?

Any help greatly appreciated, Thanks // :)

+3  A: 

You probably want something like:

float test = [txtDiscount.text floatValue];

The NSString documentation provides a list of all the built-in casts.

clee
I thought this had covered it, but I'm still getting a compilation error. Let me explain more. I have an attribute in a Core Data entity. It is declared there as type float. Core Data creates an interface to it: @property (nonatomic, retain) NSNumber * discount; and an implementation for it: @dynamic discount; I use that to access that attribute through a managed object context.This works:float test = [txtDiscount.text floatValue];NSLog(@"%f", test); This breaks:[product setDiscount:test];The compilation error is: incompatible type for argument 1 of 'setDiscount:'
Spanky
Yes, because setDiscount needs an NSNumber, not a float. Sounds like you need to do: [product setDiscount:[NSNumber numberWithFloat:[txtDiscount.text floatValue]]];But, to be brutally honest, it sounds like you really need some programming courses. You do know you shouldn't be using floats (or doubles) to represent dollar amounts, right? I hope you're not doing that...
clee
Thanks, got it worked out.
Spanky
Yes, I know. Decimal, double, float: 3 decimal including choices in Core Data with MySQL as the persistent data store. What I know of MySQL data types says that decimal is a double stored as a string, allowing for a fixed decimal point. Hence it's bigger than float and slower. And it's not necessary if you are just setting values that aren't going to be used in calculations. Then again, I guess string works in that case too. Thanks though.
Spanky
+2  A: 

A cast like this

(NSNumber *)myInstance

is telling the compiler to treat 'myInstance' as if it were an instance of class NSNumber. This may influence compile time warnings and errors. Note: - the compiler. It makes no difference to the code that is generated or run - at all. The code that you are running is still

float test = [txtDiscount text];

where the method -text is returning a pointer to an NSString and you are trying to assign it to a float variable.

see clee's answer for how to get float value from an NSString - but make sure you understand why what you were trying to do is wrong. It will help loads in the long run.

Totally agree, just wish I could see through the auto generated code fog I note in my comment to clee :)
Spanky