Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I pass an int into stringWithFormat?

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];
}
like image 796
Brennan Avatar asked Dec 21 '08 04:12

Brennan


3 Answers

Do this:

label.text = [NSString stringWithFormat:@"%d", count];
like image 167
BobbyShaftoe Avatar answered Nov 17 '22 21:11

BobbyShaftoe


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.

like image 48
Marc Charbonneau Avatar answered Nov 17 '22 21:11

Marc Charbonneau


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 NSIntegers!

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)

like image 42
squelart Avatar answered Nov 17 '22 21:11

squelart