PDA

View Full Version : Quick casting question




CocoaBean
Mar 22, 2009, 03:56 PM
Hi,

I have the following code:


#import "AppController.h"


@implementation AppController

-(IBAction)calculate:(id)sender
{
int sum;

sum = 50 + 25;

NSString *string = (@"The sum of 50 and 25 is %i", sum);

[textField setStringValue:string];
}

@end



I get the following warning:

'warning: initialization makes pointer from integer without a cast'.

I think I need to cast an integer into a string, how do I go about it in this example?

Thanks



lee1210
Mar 22, 2009, 04:00 PM
NSString *string = (@"The sum of 50 and 25 is %i", sum);
That line is not doing what you think it's doing. The parentheses are ignored, so the expression on the right side of the assignment operator is:
@"The sum of 50 and 25 is %i", sum
So a NSString literal appears, and is ignored, then the whole expression evaluates to the right hand operand of the ",", so the whole expression evaluates to to the value of sum, so this boils down to:
NSString *string = sum;

Sum is an integer, and it is being implicitly cast to an NSString *, hence the warning. You want to use +stringWithFormat:(NSString *) format, ... :
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/clm/NSString/stringWithFormat:

-Lee

CocoaBean
Mar 22, 2009, 04:21 PM
Ahh - thanks, I have it working now.
The code I have used now is:



#import "AppController.h"


@implementation AppController

-(IBAction)calculate:(id)sender
{
int sum;

sum = 50 + 25;

NSString *string = [NSString stringWithFormat:@"The sum of 50 and 25 is %i", sum];

[textField setStringValue:string];
}

@end

gnasher729
Mar 22, 2009, 04:22 PM
Take your favorite C book, read it carefully, then tell us _exactly_ what the "comma-operator" and what a "comma-expression" is. With that knowledge, read the code that you wrote again. Find out where it uses a comma operator. At that point your mistake should be obvious.

mdeh
Mar 22, 2009, 10:31 PM
Take your favorite C book, read it carefully, then tell us _exactly_ what the "comma-operator" and what a "comma-expression" is. With that knowledge, read the code that you wrote again. Find out where it uses a comma operator. At that point your mistake should be obvious.


Amazing what one can learn by lurking!!! :) Thanks gnasher and Lee PS...really nice explanations on the web too.