views:

13382

answers:

6

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];
}
+10  A: 

Do this:

label.text = [NSString stringWithFormat:@"%d", count];
BobbyShaftoe
+12  A: 

You want to use %d or %i for integers. %@ is used for objects.

It's worth noting, though, that the following code will accomplish the same task and is much clearer.

label.intValue = count;
Zach Langley
label is UILabel and your code sample did not compile in xcode.
Brennan
Gotcha. I assumed it was an NSTextField, sorry.
Zach Langley
+5  A: 

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
Good Point. Start thinking about 64 bit code now.
Abizern
+3  A: 

And for comedic value:

label.text = [NSString stringWithFormat:@"%@", [NSNumber numberWithInt:count]];

(Though it could be useful if one day you're dealing with NSNumber's)

squelart
I like a bit of humour.
Abizern
+2  A: 

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)

squelart
+1  A: 

Is the snippet you posted just a sample to show what you are trying to do?

The reason I ask is that you've named a method increment, but you seem to be using that to set the value of a text label, rather than incrementing a value.

If you are trying to do something more complicated - such as setting an integer value and having the label display this value, you could consider using bindings. e.g

You declare a property count and your increment action sets this value to whatever, and then in IB, you bind the label's text to the value of count. As long as you follow Key Value Coding (KVC) with count, you don't have to write any code to update the label's display. And from a design perspective you've got looser coupling.

Abizern