PDA

View Full Version : Casting an int to an NSString *




macfreek57
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?

Thanks



Sayer
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...

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

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

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

:D

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

lee1210
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.

-Lee