Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

CocoaBean

macrumors newbie
Original poster
Feb 23, 2009
25
0
Hi,

I have the following code:

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

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
Code:
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:
Code:
@"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:
Code:
NSString *string = sum;

Sum is an integer, and it is being implicitly cast to an NSString *, hence the warning. You want to use
Code:
+stringWithFormat:(NSString *) format, ...
:
http://developer.apple.com/document.../apple_ref/occ/clm/NSString/stringWithFormat:

-Lee
 

CocoaBean

macrumors newbie
Original poster
Feb 23, 2009
25
0
Ahh - thanks, I have it working now.
The code I have used now is:

Code:
#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

Suspended
Nov 25, 2005
17,980
5,566
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

macrumors 6502
Jan 3, 2009
345
2
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.