views:

2452

answers:

3

I need help. How come this does not work:

NSProcessInfo *process = [NSProcessInfo processInfo];
NSString *processName = [process processName];
int processId = [process processIdentifier];
NSString *processString = [NSString stringWithFormat:@"Process Name: @% Process ID: %f", processName, processId];
NSLog(processString);

But this does:

NSLog(@"Process Name: %@ Process ID: %d", [[NSProcessInfo processInfo] processName], [[NSProcessInfo processInfo] processIdentifier]);
+1  A: 

Your format string is bad: processId is an int not a float.

Use -Wformat to get rid of this kind of errors.

Nikolai Ruhe
oh! thankshow to enable -wformat in xcode?
Devoted
There's a setting for this in the target's settings pane. I dont't remember the name, but I guess you'll find it easily by searching in that pane.
Nikolai Ruhe
In Xcode, -Wformat shows up as "Typecheck Calls to printf/scanf". However, the int will be upcast just fine, and even if this is not what is intended, the problem will be easy to spot. The real problem is the formatter for the NSString — @drewh has the correct answer.
Quinn Taylor
A: 

Your format contains an error, you've swapped the @ and % for the [NSString stringWithFormat:]. It will work for the log but not for the string creation, because the format is %@ not @%.

dreamlax
+2  A: 
  • %@: Output the string form of an object (including NSString).
  • %f: Output a floating point number (float)
  • %d: Output an integral number (int)
  • %x: Output hexadecimal form of a number

Your original NSString:stringWithFormat: had two issues:

  1. @% should be %@ to output an NSString.
  2. You use %f instead of %d to output an int.
drewh
+1 Best answer. Since @% is not a valid formatter, it will throw off the format string, and you may end up (unknowingly) trying to print the NSString as a floating-point number. Odds are that you know about format specifiers and this is just a simple mistake. A good Apple reference for this is here: http://developer.apple.com/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
Quinn Taylor