Bookmark and Share

Objective-C Programming Tutorial


SoBackSanA


Chapter 5. String Objects


5.1 String Objects

The Foundation framework supports a class called NSString for character string objects. We create a constant character string object in Objective-C by placing the @ character in front of the string of double-quoted characters. So,

@"Objective-C string"
creates a constant character string object. Actually, this is a constant character string belongs to the class NSConstantString which is a subclass of the string object class NSString. To use this, we should put the following line:
#import 



The following example shows how to use the format character %@ to display an NSString object as well as shows how to define an NSSting object and assign an initial value to it.

#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>
#import <Foundation/NSAutoreleasePool.h>

int main (int argc, char *argv[])
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSString *str = @"Objective-C string";
	NSLog(@"%@",str);
 	[pool drain];
	return 0;
}

The output is:

Objective-C string

The constant string object "Objective-C string" is assigned to the NSString variable str and then it's value is displayed using NSLog.

The NSLog format characters %@ can be used to display not just NSString objects, but also cn be used to display any object. For example,

NSNumber *i = [NSNumber numberWithInteger; 100];
the NSLog call
NSLog(@"%@",i);
will produce
100

Note that the string we created is an "immutable" object whose contents cannot be changed. There is other type of string which is called "mutable" whose contents can be changed. This type of strings are handled through the NSMutable String class.




SoBackSanB