| Inherits from | |
| Conforms to | |
| Framework | /System/Library/Frameworks/Foundation.framework |
| Availability | Available in Mac OS X v10.0 and later.
|
| Declared in | NSPathUtilities.h NSString.h NSURL.h |
| Companion guides |
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. NSString is implemented to represent an array of Unicode characters (in other words, a text string).
The mutable subclass of NSString is 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).
The Application Kit also uses NSParagraphStyle and its subclass NSMutableParagraphStyle to encapsulate the paragraph or ruler attributes used by the NSAttributedString classes. Additionally, methods to support string drawing are described in NSString Additions, found in the Application Kit.
NSString is “toll-free bridged” with its Core Foundation counterpart, CFString (see CFStringRef). This means that the Core Foundation type is interchangeable in function or method calls with the bridged Foundation object. Therefore, in a method where you see an NSString * parameter, you can pass a CFStringRef, and in a function where you see a CFStringRef parameter, you can pass an NSString instance (you cast one type to the other to suppress compiler warnings). This also applies to your concrete subclasses of NSString. See Interchangeable Data Types for more information on toll-free bridging.
NSString objects represent character strings in 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 are needed for efficiency while simply appearing as arrays of characters. The cluster’s two public classes, NSString and NSMutableString, declare the programmatic interface for non-editable and editable strings, respectively.
Note: 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 an array of Unicode characters (in other words, a text string). To create and manage an immutable string, use the NSString class. To construct and manage a string that can be changed after it has been created, use NSMutableString.
The objects you create using NSString and NSMutableString are 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 a string object 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 The Unicode Standard, Version 4.0 (The Unicode Consortium, Boston: Addison-Wesley, 2003, ISBN 0-321-18578-1) and the Unicode Consortium web site: http://www.unicode.org/.
When creating an NSString object from a UTF-16-encoded string (or a byte stream interpreted as UTF-16), if the byte order is not otherwise specified, NSString assumes that the UTF-16 characters are big-endian, unless there is a BOM (byte-order mark), in which case the BOM dictates the byte order. When creating an NSString object from an array of Unicode characters, the returned string is always native-endian, since the array always contains Unicode characters in native byte order.
Over distributed-object connections, mutable string objects are passed by-reference and immutable string objects are passed by-copy.
It is possible to subclass NSString (and NSMutableString), but doing so requires providing storage facilities for the string (which is not inherited by subclasses) and implementing two primitive methods. The abstract NSString and NSMutableString classes are the public interface of a class cluster consisting mostly of private, concrete classes that create and return a string object appropriate for a given situation. Making your own concrete subclass of this cluster imposes certain requirements (discussed in “Methods to Override”).
Make sure your reasons for subclassing NSString so are valid. Instances of your subclass should represent a string and not something else. Thus the only attributes the subclass should have are the length of the character buffer it’s managing and access to individual characters in the buffer. Valid reasons for making a subclass of NSString include providing a different backing store (perhaps for better performance) or implementing some aspect of object behavior differently, such as memory management. If your purpose is to add non-essential attributes or metadata to your subclass of NSString, a better alternative would be object composition (see “Alternatives to Subclassing”). Cocoa already provides an example of this with the NSAttributedString class.
Any subclass of NSString must override the primitive instance methods length and characterAtIndex:. These methods must operate on the backing store that you provide for the characters of the string. For this backing store you can use a static array, a dynamically allocated buffer, a standard NSString object, or some other data type or mechanism. You may also choose to override, partially or fully, any other NSString method for which you want to provide an alternative implementation. For example, for better performance it is recommended that you override getCharacters:range: and give it a faster implementation.
You might want to implement an initializer for your subclass that is suited to the backing store that the subclass is managing. The NSString class does not have a designated initializer, so your initializer need only invoke the init method of super. The NSString class adopts the NSCopying, NSMutableCopying, and NSCoding protocols; if you want instances of your own custom subclass created from copying or coding, override the methods in these protocols.
Note that you shouldn’t override the hash method.
Often a better and easier alternative to making a subclass of NSString—or of any other abstract, public class of a class cluster, for that matter—is object composition. This is especially the case when your intent is to add to the subclass metadata or some other attribute that is not essential to a string object. In object composition, you would have an NSString object as one instance variable of your custom class (typically a subclass of NSObject) and one or more instance variables that store the metadata that you want for the custom object. Then just design your subclass interface to include accessor methods for the embedded string object and the metadata.
If the behavior you want to add supplements that of the existing class, you could write a category on NSString. Keep in mind, however, that this category will be in effect for all instances of NSString that you use, and this might have unintended consequences.
+ string
– init
– initWithBytes:length:encoding:
– initWithBytesNoCopy:length:encoding:freeWhenDone:
– initWithCharacters:length:
– initWithCharactersNoCopy:length:freeWhenDone:
– initWithString:
– initWithCString:encoding:
– initWithUTF8String:
– initWithFormat:
– initWithFormat:arguments:
– initWithFormat:locale:
– initWithFormat:locale:arguments:
– initWithData:encoding:
+ stringWithFormat:
+ localizedStringWithFormat:
+ stringWithCharacters:length:
+ stringWithString:
+ stringWithCString:encoding:
+ stringWithUTF8String:
+ stringWithCString: Deprecated in Mac OS X v10.4
+ stringWithCString:length: Deprecated in Mac OS X v10.4
– initWithCString: Deprecated in Mac OS X v10.4
– initWithCString:length: Deprecated in Mac OS X v10.4
– initWithCStringNoCopy:length:freeWhenDone: Deprecated in Mac OS X v10.4
+ stringWithContentsOfFile:encoding:error:
– initWithContentsOfFile:encoding:error:
+ stringWithContentsOfFile:usedEncoding:error:
– initWithContentsOfFile:usedEncoding:error:
+ stringWithContentsOfFile: Deprecated in Mac OS X v10.4
– initWithContentsOfFile: Deprecated in Mac OS X v10.4
+ stringWithContentsOfURL:encoding:error:
– initWithContentsOfURL:encoding:error:
+ stringWithContentsOfURL:usedEncoding:error:
– initWithContentsOfURL:usedEncoding:error:
+ stringWithContentsOfURL: Deprecated in Mac OS X v10.4
– initWithContentsOfURL: Deprecated in Mac OS X v10.4
– writeToFile:atomically:encoding:error:
– writeToURL:atomically:encoding:error:
– writeToFile:atomically: Deprecated in Mac OS X v10.4
– writeToURL:atomically: Deprecated in Mac OS X v10.4
– characterAtIndex:
– getCharacters:
– getCharacters:range:
– getBytes:maxLength:usedLength:encoding:options:range:remainingRange:
– cStringUsingEncoding:
– getCString:maxLength:encoding:
– UTF8String
– cString Deprecated in Mac OS X v10.4
– cStringLength Deprecated in Mac OS X v10.4
– getCString: Deprecated in Mac OS X v10.4
– getCString:maxLength: Deprecated in Mac OS X v10.4
– getCString:maxLength:range:remainingRange: Deprecated in Mac OS X v10.4
– lossyCString Deprecated in Mac OS X v10.4
– stringByAppendingFormat:
– stringByAppendingString:
– stringByPaddingToLength:withString:startingAtIndex:
– componentsSeparatedByString:
– componentsSeparatedByCharactersInSet:
– stringByTrimmingCharactersInSet:
– substringFromIndex:
– substringWithRange:
– substringToIndex:
– rangeOfCharacterFromSet:
– rangeOfCharacterFromSet:options:
– rangeOfCharacterFromSet:options:range:
– rangeOfString:
– rangeOfString:options:
– rangeOfString:options:range:
– rangeOfString:options:range:locale:
– stringByReplacingOccurrencesOfString:withString:
– stringByReplacingOccurrencesOfString:withString:options:range:
– stringByReplacingCharactersInRange:withString:
– getLineStart:end:contentsEnd:forRange:
– lineRangeForRange:
– getParagraphStart:end:contentsEnd:forRange:
– paragraphRangeForRange:
– caseInsensitiveCompare:
– localizedCaseInsensitiveCompare:
– compare:
– localizedCompare:
– compare:options:
– compare:options:range:
– compare:options:range:locale:
– hasPrefix:
– hasSuffix:
– isEqualToString:
– hash
– decomposedStringWithCanonicalMapping
– decomposedStringWithCompatibilityMapping
– precomposedStringWithCanonicalMapping
– precomposedStringWithCompatibilityMapping
+ availableStringEncodings
+ defaultCStringEncoding
+ localizedNameOfStringEncoding:
– canBeConvertedToEncoding:
– dataUsingEncoding:
– dataUsingEncoding:allowLossyConversion:
– description
– fastestEncoding
– smallestEncoding
+ pathWithComponents:
– pathComponents
– completePathIntoString:caseSensitive:matchesIntoArray:filterTypes:
– fileSystemRepresentation
– getFileSystemRepresentation:maxLength:
– isAbsolutePath
– lastPathComponent
– pathExtension
– stringByAbbreviatingWithTildeInPath
– stringByAppendingPathComponent:
– stringByAppendingPathExtension:
– stringByDeletingLastPathComponent
– stringByDeletingPathExtension
– stringByExpandingTildeInPath
– stringByResolvingSymlinksInPath
– stringByStandardizingPath
– stringsByAppendingPaths:
Returns a zero-terminated list of the encodings string objects support in the application’s environment.
+ (const NSStringEncoding *)availableStringEncodings
A zero-terminated list of the encodings string objects support in the application’s environment.
Among the more commonly used encodings are:
See the “Constants” section for a larger list and descriptions of many supported encodings. In addition to those encodings listed here, you can also use the encodings defined for CFString in Core Foundation; you just need to call the CFStringConvertEncodingToNSStringEncoding function to convert them to a usable format.
NSString.hReturns the C-string encoding assumed for any method accepting a C string as an argument.
+ (NSStringEncoding)defaultCStringEncoding
The C-string encoding assumed for any method accepting a C string as an argument.
This method returns a user-dependent encoding who value is derived from user's default language and potentially other factors. You might sometimes need to use this encoding when interpreting user documents with unknown encodings, in the absence of other hints, but in general this encoding should be used rarely, if at all. Note that some potential values might result in unexpected encoding conversions of even fairly straightforward NSString content—for example, punctuation characters with a bidirectional encoding.
Methods that accept a C string as an argument use ...CString... in the keywords for such arguments: for example, stringWithCString:—note, though, that these are deprecated. The default C-string encoding is determined from system information and can’t be changed programmatically for an individual process. See “String Encodings” for a full list of supported encodings.
NSString.hReturns a human-readable string giving the name of a given encoding.
+ (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
A string encoding.
A human-readable string giving the name of encoding in the current locale’s language.
NSString.hReturns a string created by using a given format string as a template into which the remaining argument values are substituted according to the user's default locale.
+ (id)localizedStringWithFormat:(NSString *)format ...
A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil.
Important: Raises an NSInvalidArgumentException if format is nil.
A comma-separated list of arguments to substitute into format.
A string created by using format as a template into which the following argument values are substituted according to the formatting information to the user's default locale.
This method is equivalent to using initWithFormat:locale: and passing [[NSUserDefaults standardUserDefaults] dictionaryRepresentation] as the locale argument.
As an example of formatting, this method replaces the decimal according to the locale in %f and %d substitutions, and calls descriptionWithLocale: instead of description where necessary.
This code excerpt creates a string from another string and a float:
NSString *myString = [NSString localizedStringWithFormat:@"%@: %f\n", @"Cost", 1234.56]; |
The resulting string has the value “Cost: 1234.560000\n” if the locale is en_US, and “Cost: 1234,560000\n” if the locale is fr_FR.
See Formatting String Objects for more information.
NSString.h
Returns a string built from the strings in a given array by concatenating them with a path separator between each pair.
+ (NSString *)pathWithComponents:(NSArray *)components
An array of