NSString

From GNUstepWiki
Revision as of 18:55, 3 April 2007 by Kendall (talk | contribs)
Jump to navigation Jump to search

http://www.gnustep.org/resources/documentation/Developer/Base/Reference/index.html

Strings in GNUstep use the NSString class in gnustep-base. See the reference manual for gnustep-base for more details about NSString.

Constant Strings

As you can create static instances of char* plain C, you can create strings in GNUstep that automatically flatten out to be static instances of NSString. This is done by preceding the quoted string by an "at" symbol ('@'). For example:

 NSString * myString = @"This is an example of a string.";
 NSLog(myString);

myString is now an NSString object, and can have methods called on it like any other string.

Getting a C String

You can convert an NSString object to a plain C string using the cStringUsingEncoding: method. For example:

 NSString *newString = @"This is a test string.";
 char     *theString;

 theString = [newString cStringWithEncoding:[NSString defaultCStringEncoding]];

or:

 theString = [newString UTF8String];

Note that using [string cString] is deprecated!

Reading and Writing Files With String

The following example shows how you would use files with NSString:

 // Read in the file.
 NSString *aString = [NSString stringWithContentsOfFile: @"infile.txt"];
 // Do something with our new string.
 aString = doSomething(aString);
 // And finally save our changes to a file.
 if([aString writeToFile: @"outfile" atomically: YES])
   // Success code.
 else
   // Error code.