1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Casting an int to an NSString *

Discussion in 'Mac Programming' started by macfreek57, Mar 5, 2008.

  1. macrumors 6502

    #1
    I'm trying to learn Cocoa and Objective-C. I've got a method described like so:

    Code:
    - (NSString *)buttonClicked:(int)buttonNumber;
    The function needs to return an NSString pointer. The problem is, I have an int that I need to return as the NSString. I think there are round-about ways I could do this (like make the int an NSNumber and then make that an NSString), but I'm looking for a more direct method. This seems like it would be a fairly common need as most of the Cocoa GUI components require NSStrings, so I was expecting to be able to do something like:

    Code:
    NSString *returnString;
    int myInt;
    myInt = 54;
    *returnString = @"" + myInt;
    return returnString;
    
    But that's not working. Neither is (NSString *)myInt.
    Can anyone help?

    Thanks
     
  2. macrumors 6502a

    Sayer

    #2
    You cant cast an int to an NSString pointer as NSString is an object, and you use a pointer to it so you need a piece of memory allocated for it and such.

    You could do this:

    Code:
    NSString *intString = [NSString stringWithFormat:@"%d", myInt];
    or just return it:

    Code:
    return [NSString stringWithFormat:@"%d", myInt];
    I think that's right; I'm really tired and can barely think about Objective-C right now...
     
  3. macrumors 6502

    #3
    Cool!
    Thanks! That's exactly what I needed.
     
  4. macrumors member

    #4
    Thank you!

    Sayer - you are a lifesaver, thank you for helping us newbies! This got my iPhone app running!

    :D
     
  5. macrumors newbie

    #5
    Hi,
    I got solution for int to NSString * casting.
    Now i want NSString* to int casting.
    please help me as early as possible.
     
  6. macrumors 68040

    lee1210

    #6
    Cast really only applies in terms of primitives, but...
    NSStrings respond to intValue, though in 10.5 integerValue is preferred, which returns an NSInteger rather than int.

    -Lee
     

Share This Page