4

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]);

3 Answers 3

14
  • %@: 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.
Sign up to request clarification or add additional context in comments.

1 Comment

+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: developer.apple.com/documentation/Cocoa/Conceptual/Strings/…
2

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

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

2 Comments

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

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 @%.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.