I am try to use stringWithFormat to set a numerical value on the text property of a label but the following code is not working. I cannot cast the int to NSString. I was expecting that the method would know how to automatically convert an int to NSString.
What do I need to do here?
- (IBAction) increment: (id) sender
{
int count = 1;
label.text = [NSString stringWithFormat:@"%@", count];
}
Do this:
label.text = [NSString stringWithFormat:@"%d", count];
Keep in mind that @"%d" will only work on 32 bit. Once you start using NSInteger for compatibility if you ever compile for a 64 bit platform, you should use @"%ld" as your format specifier.
Marc Charbonneau wrote:
Keep in mind that @"%d" will only work on 32 bit. Once you start using NSInteger for compatibility if you ever compile for a 64 bit platform, you should use @"%ld" as your format specifier.
Interesting, thanks for the tip, I was using @"%d" with my NSInteger
s!
The SDK documentation also recommends to cast NSInteger
to long
in this case (to match the @"%ld"), e.g.:
NSInteger i = 42;
label.text = [NSString stringWithFormat:@"%ld", (long)i];
Source: String Programming Guide for Cocoa - String Format Specifiers (Requires iPhone developer registration)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With