views:

233

answers:

1

Hi, I think this is a relatively simple question, but I don't precisely know what's happening.

I have a method that tries to build a string using NSString's stringWithFormat

It looks like this:

NSString *line1 = [NSString stringWithFormat:@"the car is %d miles away", self.ma];

In the above line "self.ma" should be an int, but in my case, I made an error and "self.ma" actually points to a NSString.

So, I understand that the line should read

NSString *line1 = [NSString stringWithFormat:@"the car is %@ miles away", self.ma];

but my question is what is the %d in the first example doing to my NSString?

If I use the debugger, I can see that in once case, "self.ma" equals "32444", but somehow the %d converts it to 1255296.

I would've guessed that the conversion of 32444 => 1255296 is some type of base-numbering conversion (hex to dec or something), but that doesn't appear to be the case.

Any idea as to what %d is doing to my string?

TIA

+3  A: 

You are actually giving it a pointer to an NSString, so when the format string expects an integer, it interprets the given bytes as an int. What is given is the address to where the NSString is in memory, and so the memory address of the string is printed out.

Brandon Bodnár
thanks very much