views:

56

answers:

2

I'm setting a UILabel to a value stored in as a NSNumber. If I do this

foo.label.text = [bar stringValue];

then I get a NSInvalidArgumentException

However if I cast by doing:

foo.label.text = (NSString *)bar;

then things work ok.

Can anyone explain why this could be the case?

+3  A: 

If bar is an NSString instance, it is normal that you get a NSInvalidArgumentException, because NSString does not respond to stringValue selector; thus the result of the stringValue is an invalid value for the text property.

Laurent Etiemble
Wouldn't that throw an "unknown selector sent to object" error?
Patrick Burleson
You got two errors: "-[NSCFString stringValue]: unrecognized selector" and a "NSInvalidArgumentException".
Laurent Etiemble
foo is a UILabel and bar is an NSNumber.
KJF
Can you print [bar class] to check that bar is a NSNumber ?
Laurent Etiemble
A: 

Using your example, if I do the following:

NSNumber *theNumber = [NSNumber numberWithInt:1];
[[self theLabel] setText:(NSString *)theNumber];

I get the NSInvalidArguementException. But if I do:

NSNumber *theNumber = [NSNumber numberWithInt:1];   
[[self theLabel] setText:[theNumber stringValue]];

My label gets set with the number 1.

Are you sure bar is NSNumber? Is foo a view with a label subview defined?

For my example, I have an IBOutlet property on an UIViewController to a UILabel. I put that label in the view using InterfaceBuilder and connected the IBOutlet.

Patrick Burleson