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]; -
You want to use
%dor%ifor 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;Brennan : label is UILabel and your code sample did not compile in xcode.Zach Langley : Gotcha. I assumed it was an NSTextField, sorry. -
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.
Abizern : Good Point. Start thinking about 64 bit code now. -
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)
Abizern : I like a bit of humour. -
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
NSIntegertolongin 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)
-
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
countand yourincrementaction sets this value to whatever, and then in IB, you bind the label's text to the value ofcount. As long as you follow Key Value Coding (KVC) withcount, you don't have to write any code to update the label's display. And from a design perspective you've got looser coupling.
0 comments:
Post a Comment