Next: Converting to and from Up: NSString Previous: Static Instances

stringWithFormat

The other main way of creating NSStrings is by means of the class method +stringWithFormat:. This is a method of the class NSString; it accepts a list of arguments which are processed in a way very similar to how the printf function of the standard C library processes its arguments; the difference is that the result of the method is not sent to the standard output, but rather it is put in a NSString which is then returned as return value of the method.

Here is an example:

int age = 25;
NSString *message;

message = [NSString stringWithFormat: @"Your age is %d", age];

message will be a NSString containing "Your age is 25".

A special feature of stringWithFormat is that it recognises the %@ conversion specification. You can use this to specify another NSString (in the same way as you would use %s to specify another C string):

NSString *first;
NSString *second;

first = @"Nicola";
second = [NSString stringWithFormat: @"My name is %@", first];
this code will cause the second variable to be set to the string My name is Nicola.

More generally, you can use the %@ specification to output a description of an object (as returned by the NSObject's -description). This is often useful in debugging, as in:

NSObject *obj = [anObject someMethod];

NSLog (@"The method returned: %@", obj);



Nicola 2002-01-13