/* Most common use */ id mutableString = [NSMutableString string]; /* May not be what you want */ id string = [NSString string];
// These are fine id party = [NSString stringWithFormat:@"Party date: %@", partyDate]; id mailto = [NSString stringWithFormat:@"mailto: %@", [person email]]; id footer = [NSString stringWithFormat: @"Interaction %@ in session %@.", numberOfInteractions, sessionNumber]; // C users, NO! This won't work. Only %@ is supported. id string = [NSString stringWithFormat:@"%d of %d %s", x, y, cString];
id mutableString = [NSMutableString stringWithString:@"Change me."];
creates an NSMutableString from a constant NSString object.
id fileContents = [NSString stringWithContentsOfFile:path];
See also writeToFile:atomically:.
id string = @"Hi"; id message = [string stringByAppendingFormat:@", %@!", guestName];
produces the string message with contents "Hi, Rena!".
id errorTag = @"Error: "; id errorString = @"premature end of file."; id errorMessage = [errorTag stringByAppendingString:errorString];
produces the string "Error: premature end of file.".
id toolString = @"wrenches, hammers, saws"; id toolArray = [toolString componentsSeparatedByString:@", "];
produce an NSArray containing the strings "wrenches", "hammers", and "saws."
See also componentsJoinedByString: (NSArray and NSMutableArray).
if ([@"hello" compare:@"Hello"] == -1) { result = [NSString stringWithFormat: @"'%@' precedes '%@' lexicographically.", @"hello", @"Hello"]; }
result in an NSString result with the contents "`hello' precedes `Hello' lexicographically."
if ([string isEqual:newString) { result = @"Found a match"; }
assign the contents "Found a match" to result if string and newString are lexicographically equal.
id message = [NSMutableString stringWithString:@"Hi"]; [message appendFormat:@", %@!", guestName];
message has the resulting contents "Hi, Rena!".
id mutableString = [NSMutableString stringWithFormat:@"Hello "]; [mutableString appendString:@"world!"];
mutableString has the resulting contents "Hello world!".
[mutableString setString:@""];
id errorLog = [NSString stringWithContentsOfFile:errorPath]; id newErrorLog = [errorLog stringByAppendingFormat:@"%@: %@.\n", timeStamp, @"premature end of file."]; [newErrorLog writeToFile:errorPath atomically:YES];
reads the contents of an error log stored in a file, appends a new error to the log, and saves the updated log to the same file.
Table of Contents Next Section