Inherits from: NSObject
Conforms to: NSCoding
NSCopying
NSMutableCopying
NSObject (NSObject)
Declared in: Foundation/NSString.h
Foundation/NSPathUtilities.h
The NSString class declares the programmatic interface for an object that manages immutable strings. (An immutable string is a text string that is defined when it is created and subsequently cannot be changed. An immutable string is implemented as array of Unicode characters (in other words, a text string). To create and manage a string that can be changed after it has been created, use NSMutableString.)
The NSString class has two primitive methods-length and characterAtIndex:-that provide the basis for all other methods in its interface. The length method returns the total number of Unicode characters in the string. characterAtIndex: gives access to each character in the string by index, with index values starting at 0.
NSString declares methods for finding and comparing strings. It also declares methods for reading numeric values from strings, for combining strings in various ways, and for converting a string to different forms (such as encoding and case changes). General use of these methods is presented in the section "Working with String Objects".
NSString objects represent character strings in OpenStep frameworks. Representing strings as objects allows you to use strings wherever you use other objects. It also provides the benefits of encapsulation, so that string objects can use whatever encoding and storage is needed for efficiency while simply appearing as arrays of characters. The cluster's two public classes, NSString and NSMutableString, declare the programmatic interface for noneditable and editable strings, respectively.
The objects you create using NSString and NSMutableStringare referred to as string objects (or, when no confusion will result, merely as strings). The term C string refers to the standard char * type. Because of the nature of class clusters, string objects aren't actual instances of the NSString or NSMutableString classes but of one of their private subclasses. Although a string object's class is private, its interface is public, as declared by these abstract superclasses, NSString and NSMutableString. The string classes adopt the NSCopying and NSMutableCopying protocols, making it convenient to convert a string of one type to the other.
A string object presents itself as an array of UnicodeÔ£® characters (Unicode is a registered trademark of Unicode, Inc.). You can determine how many characters it contains with the length method and can retrieve a specific character with the characterAtIndex: method. These two "primitive" methods provide basic access to a string object. Most use of strings, however, is at a higher level, with the strings being treated as single entities: You compare strings against one another, search them for substrings, combine them into new strings, and so on. If you need to access string objects character-by-character, you must understand the Unicode character encoding, specifically issues related to composed character sequences. For details see:
NSString provides several means for creating instances, most based around the various character encodings it supports. Although string objects always present their own contents as Unicode characters, they can convert their contents to and from many other encodings, such as 7-bit ASCII, ISO Latin 1, EUC, and Shift-JIS. The availableStringEncodings class method returns the encodings supported. You can specify an encoding explicitly when converting a C string to or from a string object, or use the default C string encoding, which varies from platform to platform and is returned by the defaultCStringEncoding class method.
The simplest way to create a string object in source code is to use either the stringWithCString: class method or the initWithCString: instance method. Each takes a standard null-terminated C string in the default C string encoding and produces a string object. As a convenience, the Objective-C language also supports the @"..." construct to create a string object constant from 7-bit ASCII encoding:
NSString *temp = @"/tmp/scratch";
Such an object is created at compile time and exists throughout your program's execution. The compiler makes such object constants unique on a per-module basis, and they're never deallocated (though you can retain and release them as you do any other object).
To get a C string from a string object, use the cString message. This returns a char * in the system's default string encoding, or raises an exception if it can't convert its contents to that encoding. The C string you receive is owned by a temporary object, though, so it will become invalid when automatic deallocation takes place. If you want to get a permanent C string, you must create a buffer and use one of the getCString:... methods to fill it. You can find out how large the buffer needs to be with the cStringLength method.
Similar methods allow you to create string objects from characters in the Unicode encoding or an arbitrary encoding, and to extract data in these encodings. initWithData:encoding: and dataUsingEncoding: perform these conversions from and to NSData objects. You can also read a string directly from a file in the Unicode or default C string encoding using the stringWithContentsOfFile: class method, and write a string using writeToFile:atomically:.
Finally, two types of method allow you to build a string from existing string objects. localizedStringWithFormat: and its siblings use a format string as a template into which the values you provide (string and other objects, numerics values, and so on) are inserted. The methods stringByAppendingString: and stringByAppendingFormat: create a new string by adding one string after another, in the second case using a format string.
In format strings, a ’Äò%' character announces a placeholder
for a value, with the characters that follow determining the kind
of value expected and how to format it. For example, a format string
of "%d houses" expects an integer value to be substituted for
the format expression "%d". NSString supports the format characters
defined for the ANSI C function printf()
,
plus ’Äò@' for any object. If the object responds to the descriptionWithLocale: message,
NSString sends that message to retrieve the text representation,
otherwise, it sends a description message.
Many compilers perform typecasting of arguments to printf()
,
so printing an integer into a %f (floating-point)
placeholder works as expected. This typecasting doesn't occur
with NSString's formatted methods, so be sure to cast your values explicitly.
Value formatting is affected by the user's current locale, which is an NSDictionary specifying number, date, and other kinds of formats. NSString uses only the locale's definition for the decimal separator (given by the key named NSDecimalSeparator). If you use a method that doesn't specify a locale, the string assumes the default locale. See "Locales" in the "Other Features" section of the Foundation Kit documentation for more information on locales.
This table summarizes the most common means of creating and converting string objects:
Source | Creation Method | Extraction Method |
Default C string encoding | stringWithCString: | getCString: (or cString) |
In code | @"..." compiler construct | |
Unicode encoding | stringWithCharacters:length: | getCharacters:length: |
Arbitrary encoding | initWithData:encoding: | dataUsingEncoding: |
File contents | stringWithContentsOfFile: | writeToFile:atomically: |
Format string | localizedStringWithFormat: | initWithFormat:locale: |
Existing strings | stringByAppendingString: | stringByAppendingFormat: |
The string classes provide methods for finding characters and substrings within strings and for comparing one string to another. These methods conform to the Unicode standard for determining whether two character sequences are equivalent. The string classes provide comparison methods that handle composed character sequences properly, though you do have the option of specifying a literal search when efficiency is important and you can guarantee some canonical form for composed character sequences.
The search and comparison methods each come in three variants. The simplest version of each searches or compares entire strings. Other variants allow you to alter the way comparison of composed character sequences is performed and to specify a specific range of characters within a string to be searched or compared. You can specify these options (not all options are available for every method):
Search Option | Effect |
NSCaseInsensitiveSearch | Ignores case distinctions among characters. |
NSLiteralSearch | Performs a byte-for-byte comparison. Differing literal sequences (such as composed character sequences) that would otherwise be considered equivalent are considered not to match. Using this option can speed some operations dramatically. |
NSBackwardsSearch | Performs searching from the end of the range toward the beginning. |
NSAnchoredSearch | Performs searching only on characters at the beginning or end of the range. No match at the beginning or end means nothing is found, even if a matching sequence of characters occurs elsewhere in the string. |
Search and comparison are currently performed as if the NSLiteralSearch option were specified. As the Unicode encoding becomes more widely used, and the need for more flexible comparison increases, the default behavior will be changed accordingly.
Substrings are only found if completely contained within the specified range. If you specify a range for a search or comparison method and don't request NSLiteralSearch, the range must not break composed character sequences on either end; if it does you could get an incorrect result. (See the method description for rangeOfComposedCharacterSequenceAtIndex: for a code sample that adjusts a range to lie on character sequence boundaries.)
The basic search and comparison methods are these:
The rangeOfString:... methods search for a substring within the receiver. The rangeOfCharacterFromSet:... methods search for individual characters from a supplied set of characters. The compare:... methods return the lexical ordering of the receiver and the supplied string. Several other methods allow you to determine whether two strings are equal or whether one is the prefix or suffix of another, but they don't have variants that allow you to specify search options or ranges.
In addition to searching and comparing strings, you can combine and divide them in various ways. The simplest way to put two strings together is to append one to the other. The stringByAppendingString: method returns a string object formed from the receiver and the argument supplied. You can also combine several strings according to a template with the initWithFormat:, stringWithFormat: and stringByAppendingFormat: methods. See "Creating and Converting String Objects" for more information.
You can extract substrings from the beginning or end of a string to a particular index, or from a specific range, with the substringToIndex:, substringFromIndex:, and substringWithRange: methods. You can also split a string into substrings (based on a separator string) with the componentsSeparatedByString: method.
Most of the NSString classes' remaining methods are for conveniences such as changing case, quickly extracting numeric values, and working with encodings. There's also a set of methods for treating strings as file system paths, described below in "Manipulating Paths". An additional class cluster, NSScanner, allows you to scan a string object for numeric and string values. Both the NSString and the NSScanner class clusters use the NSCharacterSet class cluster for search operations. See the appropriate class specifications for more information.
In addition to all the basic methods for working with character strings merely as strings, NSString also provides a rich set of methods for manipulating strings as file system paths. A string can extract a path's directory, file name, and extension, expand a tilde expression (such as "~me") or create one for the user's home directory, and clean up paths containing symbolic links, redundant slashes, and references to "." (current directory) and ".." (parent directory). These methods are listed under "Working with paths" in the Method Types section.
NSString represents paths generically with ’Äò/' as the path separator and ’Äò.' as the extension separator. Methods that accept strings as path arguments convert these generic representations to the proper system-specific form as needed. On systems with an implicit root directory, absolute paths begin with a path separator or with a tilde expression ("~/..." or "~user/..."). On systems that require explicit expression of root directories for different devices, such as Microsoft Windows 95, absolute paths begin with the name of the device (for example, "C:/Documents/Paper.doc" to represent the actual path "C:\Documents\Paper.doc"). Where a device must be specified, you can do that yourself-introducing a system dependency-or allow the string object to add a default device.
- NSCoding
- - encodeWithCoder:
- - initWithCoder:
- NSCopying
- - copyWithZone:
- NSMutableCopying
- - mutableCopyWithZone:
- Creating temporary strings
- + stringWithCString:
- + stringWithCString:length:
- + stringWithFormat:
- + localizedStringWithFormat:
- + stringWithContentsOfFile:
- + stringWithCharacters:length:
- + string
- + stringWithString:
- Initializing newly allocated strings
- - initWithCharactersNoCopy:length:freeWhenDone:
- - initWithCharacters:length:
- - initWithCStringNoCopy:length:freeWhenDone:
- - initWithCString:length:
- - initWithCString:
- - initWithString:
- - initWithFormat:
- - initWithFormat:arguments:
- - initWithFormat:locale:
- - initWithFormat:locale:arguments:
- - initWithData:encoding:
- - initWithContentsOfFile:
- - init
- Getting a string's length
- - length
- Accessing characters
- - characterAtIndex:
- - getCharacters:
- - getCharacters:range:
- Combining strings
- - stringByAppendingFormat:
- - stringByAppendingString:
- Dividing strings
- - componentsSeparatedByString:
- - substringFromIndex:
- - substringWithRange:
- - substringToIndex:
- Finding characters and substrings
- - rangeOfCharacterFromSet:
- - rangeOfCharacterFromSet:options:
- - rangeOfCharacterFromSet:options:range:
- - rangeOfString:
- - rangeOfString:options:
- - rangeOfString:options:range:
- Determining line ranges
- - getLineStart:end:contentsEnd:forRange:
- - lineRangeForRange:
- Determining composed character sequences
- - rangeOfComposedCharacterSequenceAtIndex:
- Converting string contents into a property list
- - propertyList
- - propertyListFromStringsFileFormat
- Identifying and comparing strings
- - caseInsensitiveCompare:
- - compare:
- - compare:options:
- - compare:options:range:
- - hasPrefix:
- - hasSuffix:
- - isEqualToString:
- - hash
- Getting a shared prefix
- - commonPrefixWithString:options:
- Changing case
- - capitalizedString
- - lowercaseString
- - uppercaseString
- Getting C strings
- - cString
- - lossyCString
- - cStringLength
- - getCString:
- - getCString:maxLength:
- - getCString:maxLength:range:remainingRange:
- Getting numeric values
- - doubleValue
- - floatValue
- - intValue
- Working with encodings
- + availableStringEncodings
- + defaultCStringEncoding
- + localizedNameOfStringEncoding:
- - canBeConvertedToEncoding:
- - dataUsingEncoding:
- - dataUsingEncoding:allowLossyConversion:
- - description
- - fastestEncoding
- - smallestEncoding
- Working with paths
- + pathWithComponents:
- - pathComponents
- - completePathIntoString:caseSensitive:matchesIntoArray:filterTypes:
- - fileSystemRepresentation
- - getFileSystemRepresentation:maxLength:
- - isAbsolutePath
- - lastPathComponent
- - pathExtension
- - stringByAbbreviatingWithTildeInPath
- - stringByAppendingPathComponent:
- - stringByAppendingPathExtension:
- - stringByDeletingLastPathComponent
- - stringByDeletingPathExtension
- - stringByExpandingTildeInPath
- - stringByResolvingSymlinksInPath
- - stringByStandardizingPath
- - stringsByAppendingPaths:
- Writing to a file
- - writeToFile:atomically:
+ (const NSStringEncoding *)availableStringEncodings
See the "Types and Constants" section of the Foundation Kit documentation for a complete list and descriptions of supported encodings.
See Also: + localizedNameOfStringEncoding:
+ (NSStringEncoding)defaultCStringEncoding
+ (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
+ (NSString *)localizedStringWithFormat:(NSString
*)format, ...
NSString *myString = [NSString localizedStringWithFormat:@"%@: %d\n", @"Cost", 32];
The resulting string has the value "Cost: 32\n".
See "Creating and Converting String Objects" in the class cluster description for more information.
+ (NSString *)pathWithComponents:(NSArray
*)components
On systems that require an explicit root device for an absolute path, this method add a default device specifier (such as "C:" on Windows systems).
See Also: - pathComponents
+ (id)string
See Also: - init
+ (id)stringWithCharacters:(const
unichar *)chars length:(unsigned int)length
See Also: - initWithCharacters:length:
+ (id)stringWithContentsOfFile:(NSString
*)path
nil
if
the file can't be opened.See Also: - initWithContentsOfFile:, + defaultCStringEncoding
+ (id)stringWithCString:(const
char *)cString
See Also: - initWithCString:, + defaultCStringEncoding
+ (id)stringWithCString:(const
char *)cString length:(unsigned int)length
sizeof(char)
bytes
from cString, and doesn't stop short
at a zero character.See Also: - initWithCString:length:, + defaultCStringEncoding
+ (id)stringWithFormat:(NSString
*)format, ...
See Also: - initWithFormat:
+ (id)stringWithString:(NSString
*)aString
See Also: - initWithString:
- (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
If
you plan to actually convert a string, the dataUsingEncoding:... methods return nil
on
failure, so you can avoid the overhead of invoking this method yourself
by simply trying to convert the string.
See Also: - dataUsingEncoding:allowLossyConversion:
- (NSString *)capitalizedString
Case transformations aren't guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See lowercaseString for an example.
See Also: - lowercaseString, - uppercaseString
- (NSComparisonResult)caseInsensitiveCompare:(NSString
*)aString
- (unichar)characterAtIndex:(unsigned
int)index
See Also: - getCharacters:, - getCharacters:range:
- (NSString *)commonPrefixWithString:(NSString
*)aString
options:(unsigned int)mask
See "Working with String Objects" in the class cluster description for details on these options.
See Also: - hasPrefix:
- (NSComparisonResult)compare:(NSString
*)aString
See Also: - compare:options:range:, - caseInsensitiveCompare:, - isEqualToString:
- (NSComparisonResult)compare:(NSString
*)aString options:(unsigned int)mask
See Also: - caseInsensitiveCompare:, - isEqualToString:
- (NSComparisonResult)compare:(NSString
*)aString
options:(unsigned int)mask
range:(NSRange)aRange
See "Working with String Objects" in the class cluster description for details on these options.
Raises an NSRangeException if any part of aRange lies beyond the end of the string.
See Also: - caseInsensitiveCompare:, - isEqualToString:
- (unsigned int)completePathIntoString:(NSString
**)outputName
caseSensitive:(BOOL)flag
matchesIntoArray:(NSArray **)outputArray
filterTypes:(NSArray *)filterTypes
Returns 0 if no matches are found and 1 if exactly one match is found. In the case of multiple matches, returns the actual number of matching paths if outputArray is provided, or simply a positive value if outputArray is NULL. Hence, you can check for the existence of matches without retrieving by passing NULL as outputArray
- (NSArray *)componentsSeparatedByString:(NSString
*)separator
NSString *list = @"wrenches, hammers, saws"; NSArray *listItems = [list componentsSeparatedByString:@", "];
produces an array with these contents:
Index | Substring |
0 | wrenches |
1 | hammers |
2 | saws |
If list begins with a comma and space-for example, ", wrenches, hammers, saws"-the array has these contents:
Index | Substring |
0 | (empty string) |
1 | wrenches |
2 | hammers |
3 | saws |
If list has no separators-for example, "wrenches"-the array contains the string itself, in this case "wrenches".
See Also: - componentsJoinedByString: (NSArray), - pathComponents
- (const char *)cString
Raises an NSCharacterConversionException if the receiver can't be represented in the default C string encoding without loss of information. Use canBeConvertedToEncoding: if necessary to check whether a string can be losslessly converted to the default C string encoding. If it can't, use lossyCString or dataUsingEncoding:allowLossyConversion: to get a C string representation with some loss of information.
See Also: - getCString:, - canBeConvertedToEncoding:, + defaultCStringEncoding, - cStringLength, - getCharacters:
- (unsigned int)cStringLength
Raises if the receiver
can't be represented in the default C string encoding without loss
of information. You can also use canBeConvertedToEncoding: to
check whether a string can be losslessly converted to the default
C string encoding. If it can't, use lossyCString to
get a C string representation with some loss of information, then
check its length explicitly using the ANSI function strlen()
.
See Also: - cString, - canBeConvertedToEncoding:, + defaultCStringEncoding, - length
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
allowLossyConversion:(BOOL)flag
nil
if flag is NO and
the receiver can't be converted without losing some information
(such as accents or case). If flag is YES and
the receiver can't be converted without losing some information,
some characters may be removed or altered in conversion. For example,
in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding,
the character ’ÄòˆÅ' becomes ’ÄòA', losing the accent.The result of this method, when lossless conversion is made, is the default "plain text" format for encoding and is the recommended way to save or transmit a string object.
See Also: - canBeConvertedToEncoding:
@protocol NSObject
- (NSString *)description
- (double)doubleValue
This method uses formatting information stored in the default locale; use an NSScanner for localized scanning of numeric values from a string.
See Also: - intValue, - floatValue, - scanDouble: (NSScanner)
- (NSStringEncoding)fastestEncoding
See Also: - smallestEncoding, - getCharacters:range:
- (const char *)fileSystemRepresentation
Raises an NSCharacterConversionException if the receiver can't be represented in the file system's encoding.
- (float)floatValue
This method uses formatting information stored in the default locale; use an NSScanner for localized scanning of numeric values from a string.
See Also: - doubleValue, - intValue, - scanFloat: (NSScanner)
- (void)getCharacters:(unichar
*)buffer
See Also: - length
- (void)getCharacters:(unichar
*)buffer range:(NSRange)aRange
The abstract implementation of this method uses characterAtIndex: repeatedly, correctly extracting the characters, though very inefficiently. Subclasses should override it to provide a fast implementation.
- (void)getCString:(char
*)buffer
Raises an NSCharacterConversionException if the receiver can't be represented in the default C string encoding without loss of information. Use canBeConvertedToEncoding: if necessary to check whether a string can be losslessly converted to the default C string encoding. If it can't, use lossyCString or dataUsingEncoding:allowLossyConversion: to get a C string representation with some loss of information.
See Also: - cStringLength, - canBeConvertedToEncoding:, + defaultCStringEncoding, - getCharacters:
- (void)getCString:(char
*)buffer maxLength:(unsigned int)maxLength
Raises an NSCharacterConversionException if the receiver can't be represented in the default C string encoding without loss of information. Use canBeConvertedToEncoding: if necessary to check whether a string can be losslessly converted to the default C string encoding. If it can't, use lossyCString or dataUsingEncoding:allowLossyConversion: to get a C string representation with some loss of information.
See Also: - cStringLength, - canBeConvertedToEncoding:, + defaultCStringEncoding, - getCharacters:
- (void)getCString:(char
*)buffer
maxLength:(unsigned int)maxLength
range:(NSRange)aRange
remainingRange:(NSRange *)leftoverRange
Raises an NSCharacterConversionException if the receiver can't be represented in the default C string encoding without loss of information. Use canBeConvertedToEncoding: if necessary to check whether a string can be losslessly converted to the default C string encoding. If it can't, use lossyCString or dataUsingEncoding:allowLossyConversion: to get a C string representation with some loss of information.
See Also: - cStringLength, - canBeConvertedToEncoding:, + defaultCStringEncoding, - getCharacters:
- (BOOL)getFileSystemRepresentation:(char
*)buffer maxLength:(unsigned int)maxLength
buffer must be large enough to contain maxLength chars plus a terminating zero char (which this method adds). Returns YES if buffer is successfully filled with a file system representation, NO if not (for example, if maxLength would be exceeded). Also returns NO if the receiver can't be represented in the file system's encoding.
If the system-specific path or extension separator appear in the abstract representation, the characters they're converted to depend on the system (unless they're identical to the abstract separators). On Windows 95, for example, a ’Äò\' character is converted to ’Äò/'.
See Also: - fileSystemRepresentation
+ (void)getLineStart:(unsigned
int *)startIndex
end:(unsigned int *)lineEndIndex
contentsEnd:(unsigned int *)contentsEndIndex
forRange:(NSRange)aRange
U+000D
(\r
or
CR)U+2028
(Unicode
line separator)U+000A
(\n
or
LF)U+2029
(Unicode
paragraph separator)\r\n
, in that order
(also known as CRLF)When this method returns, startIndex contains the index of the first character of the line, which is at or before the location of aRange; lineEndIndex contains the index of the first character past the line terminator; and contentsEndIndex contains the index of the first character of the line terminator itself. You may pass a NULL pointer for any of these arguments, in which case the work to compute the value isn't performed.
You can use the results of this method to construct ranges for lines by using the start index as the range's location and the difference between the end index and the start index as the range's length.
See Also: - lineRangeForRange:, - substringWithRange:
- (unsigned int)hash
- (BOOL)hasPrefix:(NSString
*)aString
See Also: - hasSuffix:, - compare:options:range:
- (BOOL)hasSuffix:(NSString
*)aString
See Also: - hasPrefix:, - compare:options:range:
- (id)init
See Also: + string
- (id)initWithCharacters:(const
unichar *)characters length:(unsigned int)length
See Also: + stringWithCharacters:length:
- (id)initWithCharactersNoCopy:(unichar
*)characters
length:(unsigned int)length
freeWhenDone:(BOOL)flag
See Also: + stringWithCharacters:length:
- (id)initWithContentsOfFile:(NSString
*)path
nil
if the file can't be opened.See Also: + stringWithContentsOfFile:, + defaultCStringEncoding
- (id)initWithCString:(const
char *)cString
To create an immutable string from an immutable CString buffer, do not attempt to use this method. Instead, use initWithCStringNoCopy:length:freeWhenDone:.
See Also: + stringWithCString:, - initWithCStringNoCopy:length:freeWhe, nDone:, + defaultCStringEncoding
- (id)initWithCString:(const
char *)cString length:(unsigned int)length
sizeof(char)
bytes
from cString, and doesn't stop
short at a zero character. cString must
contain bytes in the default C string encoding, and may not be NULL.
Returns self.See Also: + stringWithCString:length:, + defaultCStringEncoding
- (id)initWithCStringNoCopy:(char
*)cString
length:(unsigned int)length
freeWhenDone:(BOOL)flag
sizeof(char)
bytes
from cString, and doesn't stop
short at a zero character. cString must
contain characters in the default C string encoding, and may not
be NULL. The receiver becomes the owner of cString;
if flag is YES it will free the memory
when it no longer needs it, but if flag is NO it
won't. Returns self.You can use this method to create an immutable string from an immutable (const char*) C-string buffer. If you receive a warning message, you can disregard it; its purpose is simply to warn you that the C string passed as the method's first argument may be modified. If you make certain the freeWhenDone argument to initWithStringNoCopy is NO, the C string passed as the method's first argument cannot be modified, so you can safely use initWithStringNoCopy to create an immutable string from an immutable (const char*) C-string buffer.
See Also: + stringWithCString:length:, + defaultCStringEncoding
- (id)initWithData:(NSData
*)data encoding:(NSStringEncoding)encoding
- (id)initWithFormat:(NSString
*)format, ...
nil
as
the locale.See Also: + stringWithFormat:
- (id)initWithFormat:(NSString
*)format arguments:(va_list)argList
nil
as
the locale.See Also: + stringWithFormat:
- (id)initWithFormat:(NSString
*)format
locale:(NSDictionary *)dictionary, ...
See Also: + localizedStringWithFormat:
- (id)initWithFormat:(NSString
*)format
locale:(NSDictionary *)dictionary
arguments:(va_list)argList
va_list myArgs; NSDictionary *myLocale; /* Assume this exists. */ NSString *myString = [[NSString alloc] initWithFormat:@"%@: %d\n", locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] arguments:myArgs];
(Note the message construct for retrieving the user's locale.). The resulting string has the value "Cost: 32\n".
See "Creating and Converting String Objects" in the class cluster description for more information. Returns self.
See Also: - initWithFormat:arguments:
- (id)initWithString:(NSString
*)aString
See Also: + stringWithString:
- (int)intValue
This method uses formatting information stored in the default locale; use an NSScanner for localized scanning of numeric values from a string.
See Also: - doubleValue, - floatValue, - scanInt: (NSScanner)
- (BOOL)isAbsolutePath
- (BOOL)isEqualToString:(NSString
*)aString
See Also: - compare:options:range:
- (NSString *)lastPathComponent
Receiver's String Value | String Returned |
"/tmp/scratch.tiff" | "scratch.tiff" |
"/tmp/scratch" | "scratch" |
"/tmp/" | "tmp" |
"scratch" | "scratch" |
"/" | "" (an empty string) |
- (unsigned int)length
See Also: - cStringLength, - sizeWithAttributes: (NSString Additions in the Application Kit)
+ (NSRange)lineRangeForRange:(NSRange)aRange
See Also: - getLineStart:end:contentsEnd:forRange:, - substringWithRange:
- (const char *)lossyCString
See Also: - getCString:, - canBeConvertedToEncoding:, + defaultCStringEncoding, - cStringLength, - getCharacters:
- (NSString *)lowercaseString
lcString = [myString lowercaseString];
might not be equal to this:
lcString = [[myString uppercaseString] lowercaseString];
For example, the uppercase form of "ˆü" in German is "SS", so converting "eˆüen" to uppercase then lowercase produces this sequence of strings:
See Also: - capitalizedString, - uppercaseString
- (NSArray *)pathComponents
NSString *path = @"tmp/scratch"; NSArray *pathComponents = [path componentsSeparatedByString:@"/"];
produces an array with these contents:
Index | Path Component |
0 | tmp |
1 | scratch |
If the receiver begins with a slash-for example, "/tmp/scratch"-the array has these contents:
Index | Path Component |
0 | "/" |
1 | "tmp" |
2 | "scratch" |
If the receiver has no separators-for example, "scratch"-the array contains the string itself, in this case "scratch".
See Also: + pathWithComponents:, - stringByStandardizingPath, - componentsSeparatedByString:
- (NSString *)pathExtension
Receiver's String Value | String Returned |
"/tmp/scratch.tiff" | "tiff" |
"/tmp/scratch" | "" (an empty string) |
"/tmp/" | "" (an empty string) |
"/tmp/scratch..tiff" | "tiff" |
- (id)propertyList
{ Title = "Star Wars"; Director = "Lucas, George"; Cast = ( "Hamill, Mark", "Fisher, Carrie", "Ford, Harrison" ); "Thumbnail Image" = <040b7479 70656473 (many more sets of digits) 8484074e> }
See Also: - propertyListFromStringsFileFormat, + stringWithContentsOfFile:
- (NSDictionary *)propertyListFromStringsFileFormat
/*
and */
as
for ANSI C comments. Here's a short example of a strings file:/* Question in confirmation panel for quitting. */ "Confirm Quit" = "Are you sure you want to quit?"; /* Message when user tries to close unsaved document */ "Close or Save" = "Save changes before closing?"; /* Word for Cancel */ "Cancel";
See Also: - propertyList, + stringWithContentsOfFile:
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet
*)aSet
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet
*)aSet
options:(unsigned int)mask
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet
*)aSet
options:(unsigned int)mask
range:(NSRange)aRange
See "Working with String Objects" in the class cluster description for details on these options. Raises an NSRangeException if any part of aRange lies beyond the end of the string.
Because precomposed characters in aSet can match composed characters sequences in the receiver, the length of the returned range can be greater than one. For example, if you search for "ˆº" in the string "stru¬®del", the returned range is {3,2}.
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(unsigned
int)anIndex
Raises an NSRangeException if anIndex lies beyond the end of the string.
If you want to write a method to adjust an arbitrary range so it includes the composed character sequences on its boundaries, you can create a method such as this:
- (NSRange)adjustRange:(NSRange)aRange { unsigned int index, endIndex; NSRange newRange, endRange; index = aRange.location; newRange = [self rangeOfComposedCharacterSequenceAtIndex:index]; index = aRange.location + aRange.length; endRange = [self rangeOfComposedCharacterSequenceAtIndex:index]; endIndex = endRange.location + endRange.length; newRange.length = endIndex - newRange.location; return newRange; }
adjustRange: begins by correcting the location for the beginning of aRange, storing it in newRange. It then works at the end of aRange, correcting the location and storing it in endIndex. Finally, it sets the length of newRange to the difference between endIndex and the new range's location.
- (NSRange)rangeOfString:(NSString
*)aString
- (NSRange)rangeOfString:(NSString
*)aString options:(unsigned int)mask
- (NSRange)rangeOfString:(NSString
*)subString
options:(unsigned int)mask
range:(NSRange)aRange
See "Working with String Objects" in the class cluster description for details on these options. Raises an NSRangeException if any part of aRange lies beyond the end of the string. Returns a range of {NSNotFound, 0} if subString is the null string.
- (NSStringEncoding)smallestEncoding
See Also: - fastestEncoding, - getCharacters:range:
- (NSString *)stringByAbbreviatingWithTildeInPath
See Also: - stringByExpandingTildeInPath
- (NSString *)stringByAppendingFormat:(NSString
*)format, ...
See Also: - stringByAppendingString:
- (NSString *)stringByAppendingPathComponent:(NSString
*)aString
Receiver's String Value | Resulting String |
"/tmp" | "/tmp/scratch.tiff" |
"/tmp/" | "/tmp/scratch.tiff" |
"/" | "/scratch.tiff" |
"" (an empty string) | "scratch.tiff" |
See Also: - stringsByAppendingPaths:, - stringByAppendingPathExtension:, - stringByDeletingLastPathComponent
- (NSString *)stringByAppendingPathExtension:(NSString
*)string
Receiver's String Value | Resulting String |
"/tmp/scratch.old" | "/tmp/scratch.old.tiff" |
"/tmp/scratch." | "/tmp/scratch..tiff" |
"/tmp/" | "/tmp/.tiff" |
"scratch" | "scratch.tiff" |
See Also: - stringByAppendingPathComponent:, - stringByDeletingPathExtension
- (NSString *)stringByAppendingString:(NSString
*)aString
NSString *errorTag = @"Error: "; NSString *errorString = @"premature end of file."; NSString *errorMessage = [errorTag stringByAppendingString:errorString];
produces the string "Error: premature end of file.".
See Also: - stringByAppendingFormat:
- (NSString *)stringByDeletingLastPathComponent
Receiver's String Value | Resulting String |
"/tmp/scratch.tiff" | "/tmp" |
"/tmp/lock/" | "/tmp" |
"/tmp/" | "/" |
"/tmp" | "/" |
"/" | "/" |
"scratch.tiff" | "" (an empty string) |
See Also: - stringByDeletingPathExtension, - stringByAppendingPathComponent:
- (NSString *)stringByDeletingPathExtension
Receiver's String Value | Resulting String |
"/tmp/scratch.tiff" | "/tmp/scratch" |
"/tmp/" | "/tmp" |
"scratch.bundle/" | "scratch" |
"scratch..tiff" | "scratch." |
".tiff" | "" (an empty string) |
"/" | "/" |
See Also: - pathExtension, - stringByDeletingLastPathComponent
- (NSString *)stringByExpandingTildeInPath
See Also: - stringByAbbreviatingWithTildeInPath
- (NSString *)stringByResolvingSymlinksInPath
On Rhapsody and supported systems: Expands an initial tilde expression in the receiving path, then resolves all symbolic links and references to current or parent directories if possible, returning a standardized path. If the original path is absolute, all symbolic links are guaranteed to be removed; if it's a relative path, symbolic links that can't be resolved are left unresolved in the returned string. Returns self if an error occurs.
If the name of the receiving path begins
with /private
, the stringByResolvingSymlinksInPath method
strips off the /private
designator,
provided the result is the name of an existing file.
See Also: - stringByStandardizingPath, - stringByExpandingTildeInPath
- (NSString *)stringByStandardizingPath
This method can make the following changes in the provided string:
See Also: - stringByExpandingTildeInPath, - stringByResolvingSymlinksInPath
- (NSArray *)stringsByAppendingPaths:(NSArray
*)paths
- (NSString *)substringFromIndex:(unsigned
int)anIndex
See Also: - substringWithRange:, - substringToIndex:
- (NSString *)substringToIndex:(unsigned
int)anIndex
See Also: - substringFromIndex:, - substringWithRange:
- (NSString *)substringWithRange:(NSRange)aRange
See Also: - substringFromIndex:, - substringToIndex:
- (NSString *)uppercaseString
See Also: - capitalizedString, - lowercaseString
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.
See Also: + defaultCStringEncoding