View Full Version : Problem with NSString
Simon Schoelly
2004.01.25, 04:45 AM
Hi
I'm trying to learn Objective C, but now I have a problem with Strings.
NSLog(@"a %d", 4);
This returns a 4 as it should but..
NSString *StringBuffer;
StringBuffer = @"a %d", 4;
NSLog(StringBuffer);
returns a -1870134308 :blink: How can that be?
Johan
2004.01.25, 06:10 AM
I didn't even know that you could get such a statement to compile (And I was hoping that you couldn't). Mabe you should try using stringWithFormat:
NSString *StringBuffer;
StringBuffer = [NSString stringWithFormat: @"a %d", 4];
NSLog(StringBuffer);
.johan
anarchie
2004.01.25, 06:30 AM
The key here is that NSLog takes a variable number of arguments and acts like stringWithFormat: itself. The weirdness occuring in your second snippet can be attributed to the %d passed to NSLog without any corresponding argument - it uses whatever the compiler happened to leave in register r4.
The ", 4" is simply thrown away, as the comma operator resolves the left hand side (stringBuffer = @"a %d"), ignores the result, resolves the right hand side (4), then returns that. In this case it is returned in void context and ignored. Had you done something like stringBuffer = (@"a, %d", 4); this would have the effect of stringBuffer = 4, which is not a good thing in any circumstance.
Yes, like Johan said, to create NSStrings like that, you need to use +[NSString stringWithFormat:];
vBulletin® v3.8.4, Copyright ©2000-2010, Jelsoft Enterprises Ltd.