Devoted
Devoted

Reputation: 183313

iPhone: Problems with Formatted String (Objective C)

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

Upvotes: 4

Views: 10972

Answers (3)

drewh
drewh

Reputation: 10167

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

Upvotes: 14

dreamlax
dreamlax

Reputation: 95315

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

Upvotes: 0

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81848

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

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

Upvotes: 2

Related Questions