Objective-C "miscasting" string / int using stringWithFormat and% d

I think this is a relatively simple question, but I don't know exactly what is going on.

I have a method that tries to build a string using NSString 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 a mistake and "self.ma" actually points to an NSString.

So my understanding is that the line should read

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

      

but my question is What is% d in the first example running with my NSString?

If I use the debugger, I see that in one case "self.ma" is equal to "32444", but somehow% d converts it to 1255296.

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

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

TIA

+2


a source to share


1 answer


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



+4


a source







All Articles