View Full Version : Casting an int to an NSString *

Mar 6, 2008, 12:14 AM
I'm trying to learn Cocoa and Objective-C. I've got a method described like so:

- (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:

NSString *returnString;
int myInt;
myInt = 54;
*returnString = @"" + myInt;
return returnString;

But that's not working. Neither is (NSString *)myInt.
Can anyone help?


Mar 6, 2008, 12:46 AM
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:

NSString *intString = [NSString stringWithFormat:@"%d", myInt];

or just return it:

return [NSString stringWithFormat:@"%d", myInt];

I think that's right; I'm really tired and can barely think about Objective-C right now...

Mar 6, 2008, 12:49 AM
Thanks! That's exactly what I needed.

Jun 24, 2008, 10:37 AM
Thanks! That's exactly what I needed.

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


Mar 4, 2009, 10:53 PM
I got solution for int to NSString * casting.
Now i want NSString* to int casting.
please help me as early as possible.

Mar 4, 2009, 11:10 PM
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.