Quick casting question

Discussion in 'Mac Programming' started by CocoaBean, Mar 22, 2009.

  1. macrumors newbie

    Joined:
    Feb 23, 2009
    #1
    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
     
  2. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    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
     
  3. thread starter macrumors newbie

    Joined:
    Feb 23, 2009
    #3
    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
    
    
     
  4. macrumors G5

    gnasher729

    Joined:
    Nov 25, 2005
    #4
    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.
     
  5. macrumors 6502

    Joined:
    Jan 3, 2009
    #5

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

Share This Page