NSString
The NSString class and its mutable subclass, NSMutableString, provide an extensive set of APIs for working with strings, including methods for comparing, searching, and modifying strings. NSString objects are used extensively throughout Foundation and other Cocoa frameworks, serving as the basis for all textual and linguistic functionality on the platform.
NSString is “toll-free bridged” with its Core Foundation counterpart, CFStringRef. See “Toll-Free Bridging” for more information.
String Objects
An NSString object encodes a Unicode-compliant text string, represented as a sequence of UTF–16 code units. All lengths, character indexes, and ranges are expressed in terms of 16-bit platform-endian values, with index values starting at 0.
An NSString object can be initialized from or written to a C buffer, an NSData object, or the contents of an NSURL. It can also be encoded and decoded to and from ASCII, UTF–8, UTF–16, UTF–32, or any other string encoding represented by NSStringEncoding.
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.
Understanding Characters
A string object presents itself as a sequence of UTF–16 code units. You can determine how many UTF-16 code units a string object contains with the length method and can retrieve a specific UTF-16 code unit 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/. See also Characters and Grapheme Clusters in String Programming Guide.
Localized string comparisons are based on the Unicode Collation Algorithm, as tailored for different languages by CLDR (Common Locale Data Repository). Both are projects of the Unicode Consortium. Unicode is a registered trademark of Unicode, Inc.
Interpreting UTF-16-Encoded Data
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 unichar values, the returned string is always native-endian, since the array always contains UTF–16 code units in native byte order.
Subclassing Notes
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 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.
Methods to Override
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.
Alternatives to Subclassing
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.
-
Returns an empty string.
Declaration
Objective-C
+ (instancetype)stringReturn Value
An empty string.
Availability
Available in OS X v10.0 and later.
See Also
-
Returns an initialized
NSStringobject that contains no characters.Declaration
Swift
init()Objective-C
- (instancetype)initReturn Value
An initialized
NSStringobject that contains no characters. The returned object may be different from the original receiver.Availability
Available in OS X v10.0 and later.
See Also
-
Returns an initialized
NSStringobject containing a given number of bytes from a given buffer of bytes interpreted in a given encoding.Declaration
Swift
convenience init?(bytesbytes: UnsafePointer<Void>, lengthlen: Int, encodingencoding: UInt)Objective-C
- (instancetype)initWithBytes:(const void *)byteslength:(NSUInteger)lengthencoding:(NSStringEncoding)encodingParameters
bytesA buffer of bytes interpreted in the encoding specified by
encoding.lengthThe number of bytes to use from
bytes.encodingThe character encoding applied to
bytes.Return Value
An initialized
NSStringobject containinglengthbytes frombytesinterpreted using the encodingencoding. The returned object may be different from the original receiver.The return byte strings are allowed to be unterminated.
If the length of the byte string is greater than the specified length a
nilvalue is returned.Availability
Available in OS X v10.3 and later.
-
Returns an initialized
NSStringobject that contains a given number of bytes from a given buffer of bytes interpreted in a given encoding, and optionally frees the buffer.Declaration
Swift
convenience init?(bytesNoCopybytes: UnsafeMutablePointer<Void>, lengthlen: Int, encodingencoding: UInt, freeWhenDonefreeBuffer: Bool)Objective-C
- (instancetype)initWithBytesNoCopy:(void *)byteslength:(NSUInteger)lengthencoding:(NSStringEncoding)encodingfreeWhenDone:(BOOL)flagParameters
bytesA buffer of bytes interpreted in the encoding specified by
encoding.lengthThe number of bytes to use from
bytes.encodingThe character encoding of
bytes.flagIf
YEStrue, the receiver releases the memory withfree()when it no longer needs the data; ifNOfalseit won’t.Return Value
An initialized
NSStringobject containinglengthbytes frombytesinterpreted using the encodingencoding. The returned object may be different from the original receiver.Special Considerations
If an error occurs during the creation of the string, then
bytesis not freed even ifflagisYEStrue. In this case, the caller is responsible for freeing the buffer. This allows the caller to continue trying to create a string with the buffer, without having the buffer deallocated.Availability
Available in OS X v10.3 and later.
See Also
-
Returns an initialized
NSStringobject that contains a given number of characters from a given C array of UTF–16 code units.Declaration
Swift
convenience init(characterscharacters: UnsafePointer<unichar>, lengthlength: Int)Objective-C
- (instancetype)initWithCharacters:(const unichar *)characterslength:(NSUInteger)lengthParameters
characterslengthThe number of characters to use from
characters.Return Value
An initialized
NSStringobject containinglengthcharacters taken fromcharacters. The returned object may be different from the original receiver.Availability
Available in OS X v10.0 and later.
See Also
-
Returns an initialized
NSStringobject that contains a given number of characters from a given C array of UTF–16 code units.Declaration
Swift
convenience init(charactersNoCopycharacters: UnsafeMutablePointer<unichar>, lengthlength: Int, freeWhenDonefreeBuffer: Bool)Objective-C
- (instancetype)initWithCharactersNoCopy:(unichar *)characterslength:(NSUInteger)lengthfreeWhenDone:(BOOL)flagParameters
charactersA C array of UTF–16 code units.
lengthThe number of characters to use from
characters.flagIf
YEStrue, the receiver releases the memory withfree()when it no longer needs the data; ifNOfalseit won’t.Return Value
An initialized
NSStringobject that containslengthcharacters fromcharacters. The returned object may be different from the original receiver.Special Considerations
If an error occurs during the creation of the string, then
bytesis not freed even ifflagisYEStrue. In this case, the caller is responsible for freeing the buffer. This allows the caller to continue trying to create a string with the buffer, without having the buffer deallocated.Availability
Available in OS X v10.0 and later.
See Also
-
Returns an
NSStringobject initialized by copying the characters from another given string.Declaration
Swift
convenience init(stringaString: String)Objective-C
- (instancetype)initWithString:(NSString *)aStringReturn Value
An
NSStringobject initialized by copying the characters fromaString. The returned object may be different from the original receiver.Availability
Available in OS X v10.0 and later.
See Also
-
Returns an
NSStringobject initialized using the characters in a given C array, interpreted according to a given encoding.Declaration
Swift
convenience init?(CStringnullTerminatedCString: UnsafePointer<Int8>, encodingencoding: UInt)Objective-C
- (instancetype)initWithCString:(const char *)nullTerminatedCStringencoding:(NSStringEncoding)encodingParameters
nullTerminatedCStringA C array of characters. The array must end with a
NULLcharacter; intermediateNULLcharacters are not allowed.encodingThe encoding of
nullTerminatedCString.Return Value
An
NSStringobject initialized using the characters fromnullTerminatedCString. The returned object may be different from the original receiverDiscussion
If
nullTerminatedCStringis not aNULL-terminated C string, orencodingdoes not match the actual encoding, the results are undefined.Special Considerations
Only 8-bit encodings are supported, as encodings that have a greater width, such as UTF-16, may include a
NULLbyte in a single unit, which would result in the premature termination of the C string.Availability
Available in OS X v10.4 and later.
-
Returns an
NSStringobject initialized by copying the characters from a given C array of UTF8-encoded bytes.Declaration
Swift
convenience init?(UTF8StringnullTerminatedCString: UnsafePointer<Int8>)Objective-C
- (instancetype)initWithUTF8String:(const char *)bytesReturn Value
An
NSStringobject initialized by copying the bytes frombytes. The returned object may be different from the original receiver.Availability
Available in OS X v10.0 and later.
See Also
-
Returns an
NSStringobject initialized by using a given format string as a template into which the remaining argument values are substituted.Declaration
Objective-C
- (instancetype)initWithFormat:(NSString *)format,...Parameters
formatA 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....A comma-separated list of arguments to substitute into
format.Return Value
An
NSStringobject initialized by usingformatas a template into which the remaining argument values are substituted according to the system locale. The returned object may be different from the original receiver.Discussion
Invokes
initWithFormat:locale:arguments:without applying any localization. This is useful, for example, if you want to produce "non-localized" formatting which needs to be written out to files and parsed back later. To create a localized string for the user’s current locale, use the class methodlocalizedStringWithFormat:, or useinitWithFormat:locale:orinitWithFormat:locale:arguments:, passing[NSLocale currentLocale]as the locale.Availability
Available in OS X v10.0 and later.
-
Returns an
NSStringobject initialized by using a given format string as a template into which the remaining argument values are substituted without any localization. This method is meant to be called from within a variadic function, where the argument list will be available.Declaration
Swift
convenience init(formatformat: String, argumentsargList: CVaListPointer)Objective-C
- (instancetype)initWithFormat:(NSString *)formatarguments:(va_list)argListParameters
formatA 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.argListA list of arguments to substitute into
format.Return Value
An
NSStringobject initialized by usingformatas a template into which the values inargListare substituted according to the current locale. The returned object may be different from the original receiver.Discussion
Invokes
initWithFormat:locale:arguments:without applying any localization.Availability
Available in OS X v10.0 and later.
See Also
-
Returns an
NSStringobject initialized by using a given format string as a template into which the remaining argument values are substituted according to given locale.Declaration
Objective-C
- (instancetype)initWithFormat:(NSString *)formatlocale:(id)locale,...Parameters
formatA 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.localeAn
NSLocaleobject specifying the locale to use. To use the current locale, pass[NSLocale currentLocale]. To use the system locale, passnil.For legacy support, this may be an instance of
NSDictionarycontaining locale information....A comma-separated list of arguments to substitute into
format.Discussion
Invokes
initWithFormat:locale:arguments:withlocaleas the locale.Availability
Available in OS X v10.0 and later.
See Also
-
Returns an
NSStringobject initialized by using a given format string as a template into which the remaining argument values are substituted according to given locale information. This method is meant to be called from within a variadic function, where the argument list will be available.Declaration
Swift
convenience init(formatformat: String, localelocale: AnyObject?, argumentsargList: CVaListPointer)Objective-C
- (instancetype)initWithFormat:(NSString *)formatlocale:(id)localearguments:(va_list)argListParameters
formatA 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.localeAn
NSLocaleobject specifying the locale to use. To use the current locale (specified by user preferences), pass [NSLocalecurrentLocale]. To use the system locale, passnil.For legacy support, this may be an instance of
NSDictionarycontaining locale information.argListA list of arguments to substitute into
format.Return Value
An
NSStringobject initialized by usingformatas a template into which values inargListare substituted according the locale information inlocale. The returned object may be different from the original receiver.Discussion
The following Objective-C code fragment illustrates how to create a string from
myArgs, which is derived from a string object with the value “Cost:” and an int with the value 32:va_list myArgs;NSString *myString = [[NSString alloc] initWithFormat:@"%@: %d\n"locale:[NSLocale currentLocale]arguments:myArgs];
The resulting string has the value “
Cost: 32\n”.See String Programming Guide for more information.
Availability
Available in OS X v10.0 and later.
See Also
-
Returns an
NSStringobject initialized by converting given data into UTF–16 code units using a given encoding.Declaration
Objective-C
- (instancetype)initWithData:(NSData *)dataencoding:(NSStringEncoding)encodingParameters
dataAn
NSDataobject containing bytes inencodingand the default plain text format (that is, pure content with no attributes or other markups) for that encoding.encodingThe encoding used by
data.Return Value
An
NSStringobject initialized by converting the bytes indatainto UTF–16 code units usingencoding. The returned object may be different from the original receiver. Returnsnilif the initialization fails for some reason (for example ifdatadoes not represent valid data forencoding).Availability
Available in OS X v10.0 and later.
-
Returns a string created by using a given format string as a template into which the remaining argument values are substituted.
Declaration
Objective-C
+ (instancetype)stringWithFormat:(NSString *)format,...Parameters
formatA 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....A comma-separated list of arguments to substitute into
format.Return Value
A string created by using
formatas a template into which the remaining argument values are substituted without any localization.Discussion
This method is similar to
localizedStringWithFormat:, but without localization. This is useful, for example, if you want to produce non-localized formatting which needs to be written out to files and parsed back later.Availability
Available in OS X v10.0 and later.
-
Returns a string created by using a given format string as a template into which the remaining argument values are substituted according to the current locale.
Declaration
Objective-C
+ (instancetype)localizedStringWithFormat:(NSString *)format,...Parameters
formatA 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.Raises an
NSInvalidArgumentExceptionifformatisnil....A comma-separated list of arguments to substitute into
format.Return Value
A string created by using
formatas a template into which the following argument values are substituted according to the formatting information in the current locale.Discussion
This method is equivalent to using
initWithFormat:locale:and passing the current locale as the locale argument.As an example of formatting, this method replaces the decimal according to the locale in
%fand%dsubstitutions, and callsdescriptionWithLocale:instead ofdescriptionwhere 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 isen_US, and “Cost: 1234,560000\n” if the locale isfr_FR.See Formatting String Objects for more information.
Availability
Available in OS X v10.0 and later.
-
Returns a string containing a given number of characters taken from a given C array of UTF–16 code units.
Declaration
Objective-C
+ (instancetype)stringWithCharacters:(const unichar *)charslength:(NSUInteger)lengthParameters
charslengthThe number of characters to use from
chars.Return Value
A string containing
lengthUTF–16 code units taken (starting with the first) fromchars.Availability
Available in OS X v10.0 and later.
See Also
-
Returns a string created by copying the characters from another given string.
Declaration
Objective-C
+ (instancetype)stringWithString:(NSString *)aStringReturn Value
A string created by copying the characters from
aString.Availability
Available in OS X v10.0 and later.
See Also
-
Returns a string containing the bytes in a given C array, interpreted according to a given encoding.
Declaration
Objective-C
+ (instancetype)stringWithCString:(const char *)cStringencoding:(NSStringEncoding)encParameters
cStringA C array of bytes. The array must end with a
NULLbyte; intermediateNULLbytes are not allowed.encThe encoding of
cString.Return Value
A string containing the characters described in
cString.Discussion
If
cStringis not aNULL-terminated C string, orencodingdoes not match the actual encoding, the results are undefined.Special Considerations
Only 8-bit encodings are supported, as encodings that have a greater width, such as UTF-16, may include a
NULLbyte in a single unit, which would result in the premature termination of the C string.Availability
Available in OS X v10.4 and later.
See Also
-
Returns a string created by copying the data from a given C array of UTF8-encoded bytes.
Declaration
Objective-C
+ (instancetype)stringWithUTF8String:(const char *)bytesReturn Value
A string created by copying the data from
bytes.Availability
Available in OS X v10.0 and later.
See Also
-
Returns a string created by reading data from the file at a given path interpreted using a given encoding.
Declaration
Objective-C
+ (instancetype)stringWithContentsOfFile:(NSString *)pathencoding:(NSStringEncoding)encerror:(NSError * _Nullable *)errorParameters
pathA path to a file.
encThe encoding of the file at
path.errorIf an error occurs, upon returns contains an
NSErrorobject that describes the problem. If you are not interested in possible errors, pass inNULL.Return Value
A string created by reading data from the file named by
pathusing the encoding,enc. If the file can’t be opened or there is an encoding error, returnsnil.Availability
Available in OS X v10.4 and later.
-
Returns an
NSStringobject initialized by reading data from the file at a given path using a given encoding.Declaration
Objective-C
- (instancetype)initWithContentsOfFile:(NSString *)pathencoding:(NSStringEncoding)encerror:(NSError * _Nullable *)errorParameters
pathA path to a file.
encThe encoding of the file at
path.errorIf an error occurs, upon return contains an
NSErrorobject that describes the problem. If you are not interested in possible errors, pass inNULL.Return Value
An
NSStringobject initialized by reading data from the file named bypathusing the encoding,enc. The returned object may be different from the original receiver. If the file can’t be opened or there is an encoding error, returnsnil.Discussion
Availability
Available in OS X v10.4 and later.
-
Returns a string created by reading data from the file at a given path and returns by reference the encoding used to interpret the file.
Declaration
Objective-C
+ (instancetype)stringWithContentsOfFile:(NSString *)pathusedEncoding:(NSStringEncoding *)encerror:(NSError * _Nullable *)errorParameters
pathA path to a file.
encUpon return, if the file is read successfully, contains the encoding used to interpret the file at
path.errorIf an error occurs, upon returns contains an
NSErrorobject that describes the problem. If you are not interested in possible errors, you may pass inNULL.Return Value
A string created by reading data from the file named by
path. If the file can’t be opened or there is an encoding error, returnsnil.Discussion
This method attempts to determine the encoding of the file at
path.Availability
Available in OS X v10.4 and later.
-
Returns an
NSStringobject initialized by reading data from the file at a given path and returns by reference the encoding used to interpret the characters.Declaration
Swift
convenience init(contentsOfFilepath: String, usedEncodingenc: UnsafeMutablePointer<UInt>) throwsObjective-C
- (instancetype)initWithContentsOfFile:(NSString *)pathusedEncoding:(NSStringEncoding *)encerror:(NSError * _Nullable *)errorParameters
pathA path to a file.
encUpon return, if the file is read successfully, contains the encoding used to interpret the file at
path.errorIf an error occurs, upon returns contains an
NSErrorobject that describes the problem. If you are not interested in possible errors, pass inNULL.Return Value
An
NSStringobject initialized by reading data from the file named bypath. The returned object may be different from the original receiver. If the file can’t be opened or there is an encoding error, returnsnil.Discussion
Availability
Available in OS X v10.4 and later.
-
Returns a string created by reading data from a given URL interpreted using a given encoding.
Declaration
Objective-C
+ (instancetype)stringWithContentsOfURL:(NSURL *)urlencoding:(NSStringEncoding)encerror:(NSError * _Nullable *)errorParameters
urlThe URL to read.
encThe encoding of the data at
url.errorIf an error occurs, upon returns contains an
NSErrorobject that describes the problem. If you are not interested in possible errors, you may pass inNULL.Return Value
A string created by reading data from
URLusing the encoding,enc. If the URL can’t be opened or there is an encoding error, returnsnil.Availability
Available in OS X v10.4 and later.
-
Returns an
NSStringobject initialized by reading data from a given URL interpreted using a given encoding.Declaration
Objective-C
- (instancetype)initWithContentsOfURL:(NSURL *)urlencoding:(NSStringEncoding)encerror:(NSError * _Nullable *)errorParameters
urlThe URL to read.
encThe encoding of the file at
path.errorIf an error occurs, upon returns contains an
NSErrorobject that describes the problem. If you are not interested in possible errors, pass inNULL.Return Value
An
NSStringobject initialized by reading data fromurl. The returned object may be different from the original receiver. If the URL can’t be opened or there is an encoding error, returnsnil.Discussion
Availability
Available in OS X v10.4 and later.
-
Returns a string created by reading data from a given URL and returns by reference the encoding used to interpret the data.
Declaration
Objective-C
+ (instancetype)stringWithContentsOfURL:(NSURL *)urlusedEncoding:(NSStringEncoding *)encerror:(NSError * _Nullable *)errorParameters
urlThe URL from which to read data.
encUpon return, if
urlis read successfully, contains the encoding used to interpret the data.errorIf an error occurs, upon returns contains an
NSErrorobject that describes the problem. If you are not interested in possible errors, you may pass inNULL.Return Value
A string created by reading data from
url. If the URL can’t be opened or there is an encoding error, returnsnil.Discussion
This method attempts to determine the encoding at
url.Availability
Available in OS X v10.4 and later.
-
Returns an
NSStringobject initialized by reading data from a given URL and returns by reference the encoding used to interpret the data.Declaration
Swift
convenience init(contentsOfURLurl: NSURL, usedEncodingenc: UnsafeMutablePointer<UInt>) throwsObjective-C
- (instancetype)initWithContentsOfURL:(NSURL *)urlusedEncoding:(NSStringEncoding *)encerror:(NSError * _Nullable *)errorParameters
urlThe URL from which to read data.
encUpon return, if
urlis read successfully, contains the encoding used to interpret the data.errorIf an error occurs, upon returns contains an
NSErrorobject that describes the problem. If you are not interested in possible errors, pass inNULL.Return Value
An
NSStringobject initialized by reading data fromurl. Ifurlcan’t be opened or the encoding cannot be determined, returnsnil. The returned initialized object might be different from the original receiverDiscussion
To read data with an unknown encoding, pass
0as theencparameter as in:NSURL *textFileURL = …;NSStringEncoding encoding = 0;NSError *error = nil;NSString *string = [[NSString alloc] initWithContentsOfURL:textFileURL usedEncoding:&encoding error:&error];
Availability
Available in OS X v10.4 and later.
-
Writes the contents of the receiver to a file at a given path using a given encoding.
Declaration
Swift
func writeToFile(_path: String, atomicallyuseAuxiliaryFile: Bool, encodingenc: UInt) throwsObjective-C
- (BOOL)writeToFile:(NSString *)pathatomically:(BOOL)useAuxiliaryFileencoding:(NSStringEncoding)encerror:(NSError * _Nullable *)errorParameters
pathThe file to which to write the receiver. If
pathcontains a tilde (~) character, you must expand it withstringByExpandingTildeInPathbefore invoking this method.useAuxiliaryFileIf
YEStrue, the receiver is written to an auxiliary file, and then the auxiliary file is renamed topath. IfNOfalse, the receiver is written directly topath. TheYEStrueoption guarantees thatpath, if it exists at all, won’t be corrupted even if the system should crash during writing.encThe encoding to use for the output.
errorIf there is an error, upon return contains an
NSErrorobject that describes the problem. If you are not interested in details of errors, you may pass inNULL.Return Value
YEStrueif the file is written successfully, otherwiseNOfalse(if there was a problem writing to the file or with the encoding).Discussion
This method overwrites any existing file at
path.This method stores the specified encoding with the file in an extended attribute under the name
com.apple.TextEncoding. The value contains the IANA name for the encoding and theCFStringEncodingvalue for the encoding, separated by a semicolon. TheCFStringEncodingvalue is written as an ASCII string containing an unsigned 32-bit decimal integer and is not terminated by a null character. One or both of these values may be missing. Examples of the value written include the following:MACINTOSH;0UTF-8;134217984UTF-8;;3071
The methods
initWithContentsOfFile:usedEncoding:error:,initWithContentsOfURL:usedEncoding:error:,stringWithContentsOfFile:usedEncoding:error:, andstringWithContentsOfURL:usedEncoding:error:use this information to open the file using the right encoding.Availability
Available in OS X v10.4 and later.
-
Writes the contents of the receiver to the URL specified by
urlusing the specified encoding.Declaration
Objective-C
- (BOOL)writeToURL:(NSURL *)urlatomically:(BOOL)useAuxiliaryFileencoding:(NSStringEncoding)encerror:(NSError * _Nullable *)errorParameters
urlThe URL to which to write the receiver. Only file URLs are supported.
useAuxiliaryFileIf
YEStrue, the receiver is written to an auxiliary file, and then the auxiliary file is renamed tourl. IfNOfalse, the receiver is written directly tourl. TheYEStrueoption guarantees thaturl, if it exists at all, won’t be corrupted even if the system should crash during writing.The
useAuxiliaryFileparameter is ignored ifurlis not of a type that can be accessed atomically.encThe encoding to use for the output.
errorIf there is an error, upon return contains an
NSErrorobject that describes the problem. If you are not interested in details of errors, you may pass inNULL.Return Value
YEStrueif the URL is written successfully, otherwiseNOfalse(if there was a problem writing to the URL or with the encoding).Discussion
This method stores the specified encoding with the file in an extended attribute under the name
com.apple.TextEncoding. The value contains the IANA name for the encoding and theCFStringEncodingvalue for the encoding, separated by a semicolon. TheCFStringEncodingvalue is written as an ASCII string containing an unsigned 32-bit decimal integer and is not terminated by a null character. One or both of these values may be missing. Examples of the value written include the following:MACINTOSH;0UTF-8;134217984
UTF-8;;3071
The methods
initWithContentsOfFile:usedEncoding:error:,initWithContentsOfURL:usedEncoding:error:,stringWithContentsOfFile:usedEncoding:error:, andstringWithContentsOfURL:usedEncoding:error:use this information to open the file using the right encoding.Availability
Available in OS X v10.4 and later.
-
The number of UTF–16 code units in the receiver. (read-only)
Discussion
This number includes the individual characters of composed character sequences, so you cannot use this property to determine if a string will be visible when printed or how long it will appear.
Availability
Available in OS X v10.0 and later.
See Also
– lengthOfBytesUsingEncoding:sizeWithAttributes:(NSStringAdditions) -
Returns the number of bytes required to store the receiver in a given encoding.
Declaration
Objective-C
- (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)encParameters
encThe encoding for which to determine the receiver's length.
Return Value
The number of bytes required to store the receiver in the encoding
encin a non-external representation. The length does not include space for a terminatingNULLcharacter. Returns0if the specified encoding cannot be used to convert the receiver or if the amount of memory required for storing the results of the encoding conversion would exceedNSIntegerMax.Discussion
The result is exact and is returned in
O(n)time.Availability
Available in OS X v10.4 and later.
-
Returns the maximum number of bytes needed to store the receiver in a given encoding.
Declaration
Objective-C
- (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)encParameters
encThe encoding for which to determine the receiver's length.
Return Value
The maximum number of bytes needed to store the receiver in
encodingin a non-external representation. The length does not include space for a terminatingNULLcharacter. Returns0if the amount of memory required for storing the results of the encoding conversion would exceedNSIntegerMax.Discussion
The result is an estimate and is returned in
O(1)time; the estimate may be considerably greater than the actual length needed.Availability
Available in OS X v10.4 and later.
-
Returns the character at a given array position.
Declaration
Objective-C
- (unichar)characterAtIndex:(NSUInteger)indexParameters
indexThe index of the character to retrieve. The index value must not lie outside the bounds of the receiver.
Return Value
The character at the array position given by
index.Discussion
Raises an
NSRangeExceptionifindexlies beyond the end of the receiver.Availability
Available in OS X v10.0 and later.
See Also
-
Copies characters from a given range in the receiver into a given buffer.
Declaration
Swift
func getCharacters(_buffer: UnsafeMutablePointer<unichar>, rangerange: NSRange)Parameters
bufferUpon return, contains the characters from the receiver.
buffermust be large enough to contain the characters in the rangeaRange(aRange.length*sizeof(unichar)).aRangeDiscussion
This method does not add a
NULLcharacter.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.Availability
Available in OS X v10.0 and later.
-
getBytes(_:maxLength:usedLength:encoding:options:range:remainingRange:) - getBytes:maxLength:usedLength:encoding:options:range:remainingRange:Gets a given range of characters as bytes in a specified encoding.
Declaration
Swift
func getBytes(_buffer: UnsafeMutablePointer<Void>, maxLengthmaxBufferCount: Int, usedLengthusedBufferCount: UnsafeMutablePointer<Int>, encodingencoding: UInt, optionsoptions: NSStringEncodingConversionOptions, rangerange: NSRange, remainingRangeleftover: NSRangePointer) -> BoolObjective-C
- (BOOL)getBytes:(void *)buffermaxLength:(NSUInteger)maxBufferCountusedLength:(NSUInteger *)usedBufferCountencoding:(NSStringEncoding)encodingoptions:(NSStringEncodingConversionOptions)optionsrange:(NSRange)rangeremainingRange:(NSRangePointer)leftoverParameters
bufferA buffer into which to store the bytes from the receiver. The returned bytes are not
NULL-terminated.maxBufferCountThe maximum number of bytes to write to
buffer.usedBufferCountThe number of bytes used from
buffer. PassNULLif you do not need this value.encodingThe encoding to use for the returned bytes.
optionsA mask to specify options to use for converting the receiver’s contents to
encoding(if conversion is necessary).rangeThe range of characters in the receiver to get.
leftoverThe remaining range. Pass
NULLIf you do not need this value.Return Value
YEStrueif some characters were converted, otherwiseNOfalse.Discussion
Conversion might stop when the buffer fills, but it might also stop when the conversion isn't possible due to the chosen encoding.
Availability
Available in OS X v10.5 and later.
-
Returns a representation of the receiver as a C string using a given encoding.
Declaration
Swift
func cStringUsingEncoding(_encoding: UInt) -> UnsafePointer<Int8>Objective-C
- (const char *)cStringUsingEncoding:(NSStringEncoding)encodingParameters
encodingThe encoding for the returned C string.
Return Value
A C string representation of the receiver using the encoding specified by
encoding. ReturnsNULLif the receiver cannot be losslessly converted toencoding.Discussion
The returned C string is guaranteed to be valid only until either the receiver is freed, or until the current memory is emptied, whichever occurs first. You should copy the C string or use
getCString:maxLength:encoding:if it needs to store the C string beyond this time.You can use
canBeConvertedToEncoding:to check whether a string can be losslessly converted toencoding. If it can’t, you can usedataUsingEncoding:allowLossyConversion:to get a C-string representation usingencoding, allowing some loss of information (note that the data returned bydataUsingEncoding:allowLossyConversion:is not a strict C-string since it does not have aNULLterminator).Special Considerations
UTF16 and UTF32 are not considered to be C string encodings, and should not be used with this method—the results of passing
NSUTF16StringEncoding,NSUTF32StringEncoding, or any of their variants are undefined.Availability
Available in OS X v10.4 and later.
-
Converts the receiver’s content to a given encoding and stores them in a buffer.
Declaration
Swift
func getCString(_buffer: UnsafeMutablePointer<Int8>, maxLengthmaxBufferCount: Int, encodingencoding: UInt) -> BoolObjective-C
- (BOOL)getCString:(char *)buffermaxLength:(NSUInteger)maxBufferCountencoding:(NSStringEncoding)encodingParameters
bufferUpon return, contains the converted C-string plus the
NULLtermination byte. The buffer must include room formaxBufferCountbytes.maxBufferCountThe maximum number of bytes in the string to return in buffer (including the
NULLtermination byte).encodingThe encoding for the returned C string.
Return Value
YEStrueif the operation was successful, otherwiseNOfalse. ReturnsNOfalseif conversion is not possible due to encoding errors or ifbufferis too small.Discussion
Note that in the treatment of the
maxBufferCountargument, this method differs from the deprecated getCString:maxLength: method which it replaces. (The buffer should include room formaxBufferCountbytes; this number should accommodate the expected size of the return value plus theNULLtermination byte, which this method adds.)You can use
canBeConvertedToEncoding:to check whether a string can be losslessly converted toencoding. If it can’t, you can usedataUsingEncoding:allowLossyConversion:to get a C-string representation usingencoding, allowing some loss of information (note that the data returned bydataUsingEncoding:allowLossyConversion:is not a strict C-string since it does not have aNULLterminator).Availability
Available in OS X v10.4 and later.
-
UTF8String UTF8StringPropertyA null-terminated UTF8 representation of the string. (read-only)
Declaration
Swift
var UTF8String: UnsafePointer<Int8> { get }Objective-C
@property(readonly) const char *UTF8StringDiscussion
This C string is a pointer to a structure inside the string object, which may have a lifetime shorter than the string object and will certainly not have a longer lifetime. Therefore, you should copy the C string if it needs to be stored outside of the memory context in which you use this property.
Availability
Available in OS X v10.0 and later.
-
Returns the result of invoking
compare:options:with the case-insensitive option.Declaration
Swift
func caseInsensitiveCompare(_string: String) -> NSComparisonResultObjective-C
- (NSComparisonResult)caseInsensitiveCompare:(NSString *)aStringParameters
aStringThe string with which to compare the receiver.
This value must not be
nil. If this value isnil, the behavior is undefined and may change in future versions of OS X.Return Value
The result of invoking
compare:options:withNSCaseInsensitiveSearchas the only option.Discussion
This method adds the
NSCaseInsensitiveSearchoption automatically. If you are comparing strings to present to the end-user, you should typically uselocalizedCaseInsensitiveCompare:instead.Availability
Available in OS X v10.0 and later.
-
Compares the string with a given string using a case-insensitive, localized, comparison.
Declaration
Swift
func localizedCaseInsensitiveCompare(_string: String) -> NSComparisonResultObjective-C
- (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aStringParameters
aStringThe string with which to compare the receiver.
This value must not be
nil. If this value isnil, the behavior is undefined and may change in future versions of OS X.Return Value
Returns an
NSComparisonResultvalue that indicates the lexical ordering.NSOrderedAscendingthe receiver precedesaStringin lexical ordering,NSOrderedSamethe receiver andaStringare equivalent in lexical value, andNSOrderedDescendingif the receiver followsaString.Discussion
This method uses the current locale.
Availability
Available in OS X v10.0 and later.
See Also
-
Returns the result of invoking
compare:options:range:with no options and the receiver’s full extent as the range.Declaration
Swift
func compare(_string: String) -> NSComparisonResultObjective-C
- (NSComparisonResult)compare:(NSString *)aStringParameters
aStringThe string with which to compare the receiver.
This value must not be
nil. If this value isnil, the behavior is undefined and may change in future versions of OS X.Return Value
The result of invoking
compare:options:range:with no options and the receiver’s full extent as the range.Discussion
If you are comparing strings to present to the end-user, you should typically use
localizedCompare:orlocalizedCaseInsensitiveCompare:instead.Availability
Available in OS X v10.0 and later.
-
Compares the string and a given string using a localized comparison.
Declaration
Swift
func localizedCompare(_string: String) -> NSComparisonResultObjective-C
- (NSComparisonResult)localizedCompare:(NSString *)aStringParameters
aStringThe string with which to compare the receiver.
This value must not be
nil. If this value isnil, the behavior is undefined and may change in future versions of OS X.Return Value
Returns an
NSComparisonResult.NSOrderedAscendingthe receiver precedesstringin lexical ordering,NSOrderedSamethe receiver andstringare equivalent in lexical value, andNSOrderedDescendingif the receiver followsstring.Discussion
This method uses the current locale.
Availability
Available in OS X v10.0 and later.
See Also
-
Compares the string with the specified string using the given options.
Declaration
Swift
func compare(_string: String, optionsmask: NSStringCompareOptions) -> NSComparisonResultObjective-C
- (NSComparisonResult)compare:(NSString *)aStringoptions:(NSStringCompareOptions)maskParameters
aStringThe string with which to compare the receiver.
This value must not be
nil. If this value isnil, the behavior is undefined and may change in future versions of OS X.maskOptions for the search—you can combine any of the following using a C bitwise OR operator:
NSCaseInsensitiveSearch,NSLiteralSearch,NSNumericSearch. See String Programming Guide for details on these options.Return Value
The result of invoking
compare:options:range:with a given mask as the options and the receiver’s full extent as the range.Discussion
If you are comparing strings to present to the end-user, you should typically use
localizedCompare:orlocalizedCaseInsensitiveCompare:instead, or usecompare:options:range:locale:and pass the user’s locale.Availability
Available in OS X v10.0 and later.
-
Returns the result of invoking
compare:options:range:locale:with anillocale.Declaration
Swift
func compare(_string: String, optionsmask: NSStringCompareOptions, rangecompareRange: NSRange) -> NSComparisonResultObjective-C
- (NSComparisonResult)compare:(NSString *)aStringoptions:(NSStringCompareOptions)maskrange:(NSRange)rangeParameters
aStringThe string with which to compare the range of the receiver specified by
range.This value must not be
nil. If this value isnil, the behavior is undefined and may change in future versions of OS X.maskOptions for the search—you can combine any of the following using a C bitwise OR operator:
NSCaseInsensitiveSearch,NSLiteralSearch,NSNumericSearch.See String Programming Guide for details on these options.
rangeReturn Value
The result of invoking
compare:options:range:locale:with anillocale.Discussion
If you are comparing strings to present to the end-user, use
compare:options:range:locale:instead and pass the current locale.Availability
Available in OS X v10.0 and later.
-
Compares the string using the specified options and returns the lexical ordering for the range.
Declaration
Swift
func compare(_string: String, optionsmask: NSStringCompareOptions, rangecompareRange: NSRange, localelocale: AnyObject?) -> NSComparisonResultObjective-C
- (NSComparisonResult)compare:(NSString *)aStringoptions:(NSStringCompareOptions)maskrange:(NSRange)rangelocale:(id)localeParameters
aStringThe string with which to compare the range of the receiver specified by
range.This value must not be
nil. If this value isnil, the behavior is undefined and may change in future versions of OS X.maskOptions for the search—you can combine any of the following using a C bitwise OR operator:
NSCaseInsensitiveSearch,NSLiteralSearch,NSNumericSearch.See String Programming Guide for details on these options.
rangelocaleAn instance of
NSLocale. To use the current locale, pass [NSLocalecurrentLocale]. For example, if you are comparing strings to present to the end-user, use the current locale. To use the system locale, passnil.Return Value
Returns an
NSComparisonResultvalue that indicates the lexical ordering of a specified range within the receiver and a given string.NSOrderedAscendingif the substring of the receiver given byrangeprecedesaStringin lexical ordering for the locale given indict,NSOrderedSameif the substring of the receiver andaStringare equivalent in lexical value, andNSOrderedDescendingif the substring of the receiver followsaString.Discussion
The
localeargument affects both equality and ordering algorithms. For example, in some locales, accented characters are ordered immediately after the base; other locales order them after “z”.Special Considerations
Prior to OS X v10.5, the
localeargument was an instance ofNSDictionary. On OS X v10.5 and later, if you pass an instance ofNSDictionarythe current locale is used instead.Availability
Available in OS X v10.0 and later.
-
Compares strings as sorted by the Finder.
Declaration
Swift
func localizedStandardCompare(_string: String) -> NSComparisonResultObjective-C
- (NSComparisonResult)localizedStandardCompare:(NSString *)stringParameters
stringThe string to compare with the receiver.
Return Value
The result of the comparison.
Discussion
This method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact sorting behavior of this method is different under different locales and may be changed in future releases. This method uses the current locale.
Availability
Available in OS X v10.6 and later.
-
Returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver.
Declaration
Objective-C
- (BOOL)hasPrefix:(NSString *)aStringParameters
aStringA string.
Return Value
YEStrueifaStringmatches the beginning characters of the receiver, otherwiseNOfalse. ReturnsNOfalseifaStringis empty.Discussion
This method is a convenience for comparing strings using the
NSAnchoredSearchoption. See String Programming Guide for more information.Availability
Available in OS X v10.0 and later.
See Also
-
Returns a Boolean value that indicates whether a given string matches the ending characters of the receiver.
Declaration
Objective-C
- (BOOL)hasSuffix:(NSString *)aStringParameters
aStringA string.
Return Value
YEStrueifaStringmatches the ending characters of the receiver, otherwiseNOfalse. ReturnsNOfalseifaStringis empty.Discussion
This method is a convenience for comparing strings using the
NSAnchoredSearchandNSBackwardsSearchoptions. See String Programming Guide for more information.Availability
Available in OS X v10.0 and later.
See Also
-
Returns a Boolean value that indicates whether a given string is equal to the receiver using a literal Unicode-based comparison.
Declaration
Objective-C
- (BOOL)isEqualToString:(NSString *)aStringParameters
aStringThe string with which to compare the receiver.
Return Value
YEStrueifaStringis equivalent to the receiver (if they have the same id or if they areNSOrderedSamein a literal comparison), otherwiseNOfalse.Discussion
The comparison uses the canonical representation of strings, which for a particular string is the length of the string plus the UTF–16 code units that make up the string. When this method compares two strings, if the individual Unicodes are the same, then the strings are equal, regardless of the backing store. “Literal” when applied to string comparison means that various Unicode decomposition rules are not applied and UTF–16 code units are individually compared. So, for instance, “Ö” represented as the composed character sequence “O” and umlaut would not compare equal to “Ö” represented as one Unicode character.
Special Considerations
When you know both objects are strings, this method is a faster way to check equality than
isEqual:.Availability
Available in OS X v10.0 and later.
See Also
-
An unsigned integer that can be used as a hash table address. (read-only)
Discussion
If two string objects are equal (as determined by the
isEqualToString:method), they must have the same hash value. This property fulfills this requirement.You should not rely on this property having the same hash value across releases of OS X.
Availability
Available in OS X v10.0 and later.
-
Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments.
Declaration
Objective-C
- (NSString *)stringByAppendingFormat:(NSString *)format,...Parameters
formatA format string. See Formatting String Objects for more information. This value must not be
nil....A comma-separated list of arguments to substitute into
format.Return Value
A string made by appending to the receiver a string constructed from
formatand the following arguments, in the manner ofstringWithFormat:.Availability
Available in OS X v10.0 and later.
See Also
-
Returns a new string made by appending a given string to the receiver.
Declaration
Objective-C
- (NSString *)stringByAppendingString:(NSString *)aStringReturn Value
A new string made by appending
aStringto the receiver.Discussion
This code excerpt, for example:
NSString *errorTag = @"Error: ";NSString *errorString = @"premature end of file.";NSString *errorMessage = [errorTag stringByAppendingString:errorString];
produces the string “
Error: premature end of file.”.Availability
Available in OS X v10.0 and later.
See Also
-
stringByPaddingToLength(_:withString:startingAtIndex:) - stringByPaddingToLength:withString:startingAtIndex:Returns a new string formed from the receiver by either removing characters from the end, or by appending as many occurrences as necessary of a given pad string.
Declaration
Swift
func stringByPaddingToLength(_newLength: Int, withStringpadString: String, startingAtIndexpadIndex: Int) -> StringObjective-C
- (NSString *)stringByPaddingToLength:(NSUInteger)newLengthwithString:(NSString *)padStringstartingAtIndex:(NSUInteger)padIndexParameters
newLengthThe new length for the receiver.
padStringThe string with which to extend the receiver.
padIndexThe index in
padStringfrom which to start padding.Return Value
A new string formed from the receiver by either removing characters from the end, or by appending as many occurrences of
padStringas necessary.Discussion
Here are some examples of usage:
[@"abc" stringByPaddingToLength: 9 withString: @"." startingAtIndex:0];// Results in "abc......"[@"abc" stringByPaddingToLength: 2 withString: @"." startingAtIndex:0];// Results in "ab"[@"abc" stringByPaddingToLength: 9 withString: @". " startingAtIndex:1];// Results in "abc . . ."// Notice that the first character in the padding is " "
Availability
Available in OS X v10.2 and later.
-
Returns an array containing substrings from the receiver that have been divided by a given separator.
Declaration
Objective-C
- (NSArray<NSString *> *)componentsSeparatedByString:(NSString *)separatorParameters
separatorThe separator string.
Return Value
An
NSArrayobject containing substrings from the receiver that have been divided byseparator.Discussion
The substrings in the array appear in the order they did in the receiver. Adjacent occurrences of the separator string produce empty strings in the result. Similarly, if the string begins or ends with the separator, the first or last substring, respectively, is empty. For example, this code fragment:
NSString *list = @"Karin, Carrie, David";NSArray *listItems = [list componentsSeparatedByString:@", "];
produces an array
{ @"Karin", @"Carrie", @"David"" }.If
listbegins with a comma and space—for example,@", Norman, Stanley, Fletcher"—the array has these contents:{ @"", @"Norman", @"Stanley", @"Fletcher" }If
listhas no separators—for example,"Karin"—the array contains the string itself, in this case{ @"Karin" }.Availability
Available in OS X v10.0 and later.
See Also
-
Returns an array containing substrings from the receiver that have been divided by characters in a given set.
Declaration
Swift
func componentsSeparatedByCharactersInSet(_separator: NSCharacterSet) -> [String]Objective-C
- (NSArray<NSString *> *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separatorParameters
separatorA character set containing the characters to to use to split the receiver. Must not be
nil.Return Value
An
NSArrayobject containing substrings from the receiver that have been divided by characters inseparator.Discussion
The substrings in the array appear in the order they did in the receiver. Adjacent occurrences of the separator characters produce empty strings in the result. Similarly, if the string begins or ends with separator characters, the first or last substring, respectively, is empty.
Availability
Available in OS X v10.5 and later.
-
Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
Declaration
Swift
func stringByTrimmingCharactersInSet(_set: NSCharacterSet) -> StringObjective-C
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)setParameters
setA character set containing the characters to remove from the receiver.
setmust not benil.Return Value
A new string made by removing from both ends of the receiver characters contained in
set. If the receiver is composed entirely of characters fromset, the empty string is returned.Discussion
Use
whitespaceCharacterSetorwhitespaceAndNewlineCharacterSetto remove whitespace around strings.Availability
Available in OS X v10.2 and later.
-
Returns a new string containing the characters of the receiver from the one at a given index to the end.
Declaration
Objective-C
- (NSString *)substringFromIndex:(NSUInteger)anIndexParameters
anIndexAn index. The value must lie within the bounds of the receiver, or be equal to the length of the receiver.
Raises an
NSRangeExceptionif (anIndex- 1) lies beyond the end of the receiver.Return Value
A new string containing the characters of the receiver from the one at
anIndexto the end. IfanIndexis equal to the length of the string, returns an empty string.Availability
Available in OS X v10.0 and later.
-
Returns a string object containing the characters of the receiver that lie within a given range.
Declaration
Objective-C
- (NSString *)substringWithRange:(NSRange)aRangeParameters
aRangeA range. The range must not exceed the bounds of the receiver.
Raises an
NSRangeExceptionif (aRange.location- 1) or (aRange.location+aRange.length- 1) lies beyond the end of the receiver.Return Value
A string object containing the characters of the receiver that lie within
aRange.Special Considerations
This method detects all invalid ranges (including those with negative lengths). For applications linked against OS X v10.6 and later, this error causes an exception; for applications linked against earlier releases, this error causes a warning, which is displayed just once per application execution.
Availability
Available in OS X v10.0 and later.
-
Returns a new string containing the characters of the receiver up to, but not including, the one at a given index.
Declaration
Objective-C
- (NSString *)substringToIndex:(NSUInteger)anIndexParameters
anIndexAn index. The value must lie within the bounds of the receiver, or be equal to the length of the receiver.
Raises an
NSRangeExceptionif (anIndex- 1) lies beyond the end of the receiver.Return Value
A new string containing the characters of the receiver up to, but not including, the one at
anIndex. IfanIndexis equal to the length of the string, returns a copy of the receiver.Availability
Available in OS X v10.0 and later.
-
Returns whether the receiver contains a given string by performing a case-sensitive, locale-unaware search.
Declaration
Objective-C
- (BOOL)containsString:(NSString *)strParameters
strThe string to search for. This value must not be
nil.Return Value
YEStrueif the receiver containsstr, otherwiseNOfalse.Discussion
Calling this method is equivalent to calling
rangeOfString:options:with no options.Availability
Available in OS X v10.10 and later.
-
Returns whether the receiver contains a given string by performing a case-insensitive, locale-aware search.
Declaration
Objective-C
- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)strParameters
strThe string to search for. This value must not be
nil.Return Value
YEStrueif the receiver containsstr, otherwiseNOfalse.Discussion
Calling this method is equivalent to calling
rangeOfString:options:with theNSCaseInsensitiveSearchoption.Availability
Available in OS X v10.10 and later.
-
Returns whether the receiver contains a given string by performing a case and diacritic insensitive, locale-aware search.
Declaration
Objective-C
- (BOOL)localizedStandardContainsString:(NSString *)strParameters
strThe string to search for. This value must not be
nil.Return Value
YEStrueif the receiver containsstr, otherwiseNOfalse.Availability
Available in OS X v10.11 and later.
-
Finds and returns the range of the first occurrence of a given string within the receiver by performing a case and diacritic insensitive, locale-aware search.
Declaration
Objective-C
- (NSRange)localizedStandardRangeOfString:(NSString *)strParameters
strThe string to search for. This value must not be
nil.Return Value
The range of the first occurrence of
strin the receiver. Returns{NSNotFound, 0}ifstris not found.Availability
Available in OS X v10.11 and later.
-
Finds and returns the range in the receiver of the first character from a given character set.
Declaration
Swift
func rangeOfCharacterFromSet(_searchSet: NSCharacterSet) -> NSRangeObjective-C
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSetParameters
aSetA character set. This value must not be
nil.Raises an
NSInvalidArgumentExceptionifaSetisnil.Return Value
The range in the receiver of the first character found from
aSet. Returns a range of{NSNotFound, 0}if none of the characters inaSetare found.Discussion
Invokes
rangeOfCharacterFromSet:options:with no options.Availability
Available in OS X v10.0 and later.
-
Finds and returns the range in the receiver of the first character, using given options, from a given character set.
Declaration
Swift
func rangeOfCharacterFromSet(_searchSet: NSCharacterSet, optionsmask: NSStringCompareOptions) -> NSRangeObjective-C
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSetoptions:(NSStringCompareOptions)maskParameters
aSetA character set. This value must not be
nil.Raises an
NSInvalidArgumentExceptionifaSetisnil.maskA mask specifying search options. The following options may be specified by combining them with the C bitwise
ORoperator:NSAnchoredSearch,NSBackwardsSearch.Return Value
The range in the receiver of the first character found from
aSet. Returns a range of{NSNotFound, 0}if none of the characters inaSetare found.Discussion
Invokes
rangeOfCharacterFromSet:options:range:withmaskfor the options and the entire extent of the receiver for the range.Availability
Available in OS X v10.0 and later.
-
Finds and returns the range in the receiver of the first character from a given character set found in a given range with given options.
Declaration
Swift
func rangeOfCharacterFromSet(_searchSet: NSCharacterSet, optionsmask: NSStringCompareOptions, rangesearchRange: NSRange) -> NSRangeObjective-C
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSetoptions:(NSStringCompareOptions)maskrange:(NSRange)aRangeParameters
aSetA character set. This value must not be
nil.Raises an
NSInvalidArgumentExceptionifaSetisnil.maskA mask specifying search options. The following options may be specified by combining them with the C bitwise
ORoperator:NSAnchoredSearch,NSBackwardsSearch.aRangeThe range in which to search.
aRangemust not exceed the bounds of the receiver.Raises an
NSRangeExceptionifaRangeis invalid.Return Value
The range in the receiver of the first character found from
aSetwithinaRange. Returns a range of{NSNotFound, 0}if none of the characters inaSetare found.Discussion
This method does not perform any Unicode normalization on the receiver, so canonically equivalent forms will not be matched. For example, searching the string “strüdel”—containing the decomposed characters “
u” (U+0075 LATIN SMALL LETTER U) and “¨” (U+0308 COMBINING DIAERESIS)—with a character set containing the precomposed character “ü” (U+00FC LATIN SMALL LETTER U WITH DIAERESIS) would return the range{NSNotFound, 0}, because none of the characters in the set are found.Special Considerations
This method detects all invalid ranges (including those with negative lengths). For applications linked against OS X v10.6 and later, this error causes an exception; for applications linked against earlier releases, this error causes a warning, which is displayed just once per application execution.
Availability
Available in OS X v10.0 and later.
-
Finds and returns the range of the first occurrence of a given string within the receiver.
Declaration
Objective-C
- (NSRange)rangeOfString:(NSString *)aStringParameters
aStringThe string to search for. This value must not be
nil.Raises an
NSInvalidArgumentExceptionifaStringisnil.Return Value
An
NSRangestructure giving the location and length in the receiver of the first occurrence ofaString. Returns{NSNotFound, 0}ifaStringis not found or is empty (@"").Discussion
Invokes
rangeOfString:options:with no options.Availability
Available in OS X v10.0 and later.
-
Finds and returns the range of the first occurrence of a given string within the receiver, subject to given options.
Declaration
Swift
func rangeOfString(_searchString: String, optionsmask: NSStringCompareOptions) -> NSRangeObjective-C
- (NSRange)rangeOfString:(NSString *)aStringoptions:(NSStringCompareOptions)maskParameters
aStringmaskA mask specifying search options. The following options may be specified by combining them with the C bitwise
ORoperator:NSCaseInsensitiveSearch,NSLiteralSearch,NSBackwardsSearch,NSAnchoredSearch. See String Programming Guide for details on these options.Return Value
An
NSRangestructure giving the location and length in the receiver of the first occurrence ofaString, modulo the options inmask. Returns{NSNotFound, 0}ifaStringis not found or is empty (@"").Discussion
Invokes
rangeOfString:options:range:with the options specified bymaskand the entire extent of the receiver as the range.Availability
Available in OS X v10.0 and later.
-
Finds and returns the range of the first occurrence of a given string, within the given range of the receiver, subject to given options.
Declaration
Swift
func rangeOfString(_searchString: String, optionsmask: NSStringCompareOptions, rangesearchRange: NSRange) -> NSRangeObjective-C
- (NSRange)rangeOfString:(NSString *)aStringoptions:(NSStringCompareOptions)maskrange:(NSRange)aRangeParameters
aStringThe string for which to search. This value must not be
nil.Raises an
NSInvalidArgumentExceptionifaStringisnil.maskA mask specifying search options. The following options may be specified by combining them with the C bitwise
ORoperator:NSCaseInsensitiveSearch,NSLiteralSearch,NSBackwardsSearch,NSAnchoredSearch. See String Programming Guide for details on these options.aRangeThe range within the receiver for which to search for
aString.Raises an
NSRangeExceptionifaRangeis invalid.Return Value
An
NSRangestructure giving the location and length in the receiver ofaStringwithinaRangein the receiver, modulo the options inmask. The range returned is relative to the start of the string, not to the passed-in range. Returns{NSNotFound, 0}ifaStringis not found or is empty (@"").Discussion
The length of the returned range and that of
aStringmay differ if equivalent composed character sequences are matched.Special Considerations
This method detects all invalid ranges (including those with negative lengths). For applications linked against OS X v10.6 and later, this error causes an exception; for applications linked against earlier releases, this error causes a warning, which is displayed just once per application execution.
Availability
Available in OS X v10.0 and later.
-
Finds and returns the range of the first occurrence of a given string within a given range of the receiver, subject to given options, using the specified locale, if any.
Declaration
Swift
func rangeOfString(_searchString: String, optionsmask: NSStringCompareOptions, rangesearchRange: NSRange, localelocale: NSLocale?) -> NSRangeObjective-C
- (NSRange)rangeOfString:(NSString *)aStringoptions:(NSStringCompareOptions)maskrange:(NSRange)aRangelocale:(NSLocale *)localeParameters
aStringThe string for which to search. This value must not be
nil.Raises an
NSInvalidArgumentExceptionifaStringisnil.maskA mask specifying search options. The following options may be specified by combining them with the C bitwise
ORoperator:NSCaseInsensitiveSearch,NSLiteralSearch,NSBackwardsSearch,NSAnchoredSearch. See String Programming Guide for details on these options.aRangeThe range within the receiver for which to search for
aString.Raises an
NSRangeExceptionifaRangeis invalid.localeThe locale to use when comparing the receiver with
aString. To use the current locale, pass [NSLocalecurrentLocale]. To use the system locale, passnil.The locale argument affects the equality checking algorithm. For example, for the Turkish locale, case-insensitive compare matches “I” to “ı” (Unicode code point U+0131, Latin Small Dotless I), not the normal “i” character.
Return Value
An
NSRangestructure giving the location and length in the receiver ofaStringwithinaRangein the receiver, modulo the options inmask. The range returned is relative to the start of the string, not to the passed-in range. Returns{NSNotFound, 0}ifaStringis not found or is empty (@"").Discussion
The length of the returned range and that of
aStringmay differ if equivalent composed character sequences are matched.Special Considerations
This method detects all invalid ranges (including those with negative lengths). For applications linked against OS X v10.6 and later, this error causes an exception; for applications linked against earlier releases, this error causes a warning, which is displayed just once per application execution.
Availability
Available in OS X v10.5 and later.
-
Enumerates all the lines in a string.
Declaration
Swift
func enumerateLinesUsingBlock(_block: (String, UnsafeMutablePointer<ObjCBool>) -> Void)Objective-C
- (void)enumerateLinesUsingBlock:(void (^)(NSString *line, BOOL *stop))blockParameters
blockThe block executed for the enumeration.
The block takes two arguments:
lineThe current line of the string being enumerated. The line contains just the contents of the line, without the line terminators. See
getLineStart:end:contentsEnd:forRange:for a discussion of line terminators.stopA reference to a Boolean value that the block can use to stop the enumeration by setting
*stop = YES; it should not touch*stopotherwise.Availability
Available in OS X v10.6 and later.
-
Enumerates the substrings of the specified type in the specified range of the string.
Declaration
Swift
func enumerateSubstringsInRange(_range: NSRange, optionsopts: NSStringEnumerationOptions, usingBlockblock: (String?, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void)Objective-C
- (void)enumerateSubstringsInRange:(NSRange)rangeoptions:(NSStringEnumerationOptions)optsusingBlock:(void (^)(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))blockParameters
rangeThe range within the string to enumerate substrings.
optsOptions specifying types of substrings and enumeration styles.
blockThe block executed for the enumeration.
The block takes four arguments:
substringThe enumerated string.
substringRangeThe range of the enumerated string in the receiver.
enclosingRangeThe range that includes the substring as well as any separator or filler characters that follow. For instance, for lines,
enclosingRangecontains the line terminators. TheenclosingRangefor the first string enumerated also contains any characters that occur before the string. Consecutive enclosing ranges are guaranteed not to overlap, and every single character in the enumerated range is included in one and only one enclosing range.stopA reference to a Boolean value that the block can use to stop the enumeration by setting
*stop = YES; it should not touch*stopotherwise.Discussion
If this method is sent to an instance of
NSMutableString, mutation (deletion, addition, or change) is allowed, as long as it is withinenclosingRange. After a mutation, the enumeration continues with the range immediately following the processed range, after the length of the processed range is adjusted for the mutation. (The enumerator assumes any change in length occurs in the specified range.)For example, if the block is called with a range starting at location N, and the block deletes all the characters in the supplied range, the next call will also pass N as the index of the range. This is the case even if mutation of the previous range changes the string in such a way that the following substring would have extended to include the already enumerated range. For example, if the string "Hello World" is enumerated via words, and the block changes "Hello " to "Hello", thus forming "HelloWorld", the next enumeration will return "World" rather than "HelloWorld".
Availability
Available in OS X v10.6 and later.
-
stringByReplacingOccurrencesOfString(_:withString:) - stringByReplacingOccurrencesOfString:withString:Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
Declaration
Swift
func stringByReplacingOccurrencesOfString(_target: String, withStringreplacement: String) -> StringObjective-C
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)targetwithString:(NSString *)replacementParameters
targetThe string to replace.
replacementThe string with which to replace
target.Return Value
A new string in which all occurrences of
targetin the receiver are replaced byreplacement.Discussion
Invokes
stringByReplacingOccurrencesOfString:withString:options:range:with0options and range of the whole string.Availability
Available in OS X v10.5 and later.
-
stringByReplacingOccurrencesOfString(_:withString:options:range:) - stringByReplacingOccurrencesOfString:withString:options:range:Returns a new string in which all occurrences of a target string in a specified range of the receiver are replaced by another given string.
Declaration
Swift
func stringByReplacingOccurrencesOfString(_target: String, withStringreplacement: String, optionsoptions: NSStringCompareOptions, rangesearchRange: NSRange) -> StringObjective-C
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)targetwithString:(NSString *)replacementoptions:(NSStringCompareOptions)optionsrange:(NSRange)searchRangeParameters
targetThe string to replace.
replacementThe string with which to replace
target.optionsA mask of options to use when comparing
targetwith the receiver. Pass0to specify no options.searchRangeThe range in the receiver in which to search for
target.Return Value
A new string in which all occurrences of
target, matched usingoptions, insearchRangeof the receiver are replaced byreplacement.Availability
Available in OS X v10.5 and later.
-
Returns a new string in which the characters in a specified range of the receiver are replaced by a given string.
Declaration
Swift
func stringByReplacingCharactersInRange(_range: NSRange, withStringreplacement: String) -> StringObjective-C
- (NSString *)stringByReplacingCharactersInRange:(NSRange)rangewithString:(NSString *)replacementParameters
rangeA range of characters in the receiver.
replacementThe string with which to replace the characters in
range.Return Value
A new string in which the characters in
rangeof the receiver are replaced byreplacement.Availability
Available in OS X v10.5 and later.
-
Returns by reference the beginning of the first line and the end of the last line touched by the given range.
Declaration
Swift
func getLineStart(_startPtr: UnsafeMutablePointer<Int>, endlineEndPtr: UnsafeMutablePointer<Int>, contentsEndcontentsEndPtr: UnsafeMutablePointer<Int>, forRangerange: NSRange)Objective-C
- (void)getLineStart:(NSUInteger *)startIndexend:(NSUInteger *)lineEndIndexcontentsEnd:(NSUInteger *)contentsEndIndexforRange:(NSRange)aRangeParameters
startIndexUpon return, contains the index of the first character of the line containing the beginning of
aRange. PassNULLif you do not need this value (in which case the work to compute the value isn’t performed).lineEndIndexUpon return, contains the index of the first character past the terminator of the line containing the end of
aRange. PassNULLif you do not need this value (in which case the work to compute the value isn’t performed).contentsEndIndexUpon return, contains the index of the first character of the terminator of the line containing the end of
aRange. PassNULLif you do not need this value (in which case the work to compute the value isn’t performed).aRangeA range within the receiver. The value must not exceed the bounds of the receiver.
Raises an
NSRangeExceptionifaRangeis invalid.Discussion
A line is delimited by any of these characters, the longest possible sequence being preferred to any shorter:
U+000AUnicode Character 'LINE FEED (LF)' (\n)U+000DUnicode Character 'CARRIAGE RETURN (CR)' (\r)U+0085Unicode Character 'NEXT LINE (NEL)'U+2028Unicode Character 'LINE SEPARATOR'U+2029Unicode Character 'PARAGRAPH SEPARATOR'\r\n, in that order (also known asCRLF)
If
aRangeis contained with a single line, of course, the returned indexes all belong to that line. 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.Special Considerations
This method detects all invalid ranges (including those with negative lengths). For applications linked against OS X v10.6 and later, this error causes an exception; for applications linked against earlier releases, this error causes a warning, which is displayed just once per application execution.
Availability
Available in OS X v10.0 and later.
-
Returns the range of characters representing the line or lines containing a given range.
Declaration
Parameters
aRangeA range within the receiver. The value must not exceed the bounds of the receiver.
Return Value
The range of characters representing the line or lines containing
aRange, including the line termination characters. SeegetLineStart:end:contentsEnd:forRange:for a discussion of line terminators.Availability
Available in OS X v10.0 and later.
-
Returns by reference the beginning of the first paragraph and the end of the last paragraph touched by the given range.
Declaration
Swift
func getParagraphStart(_startPtr: UnsafeMutablePointer<Int>, endparEndPtr: UnsafeMutablePointer<Int>, contentsEndcontentsEndPtr: UnsafeMutablePointer<Int>, forRangerange: NSRange)Objective-C
- (void)getParagraphStart:(NSUInteger *)startIndexend:(NSUInteger *)endIndexcontentsEnd:(NSUInteger *)contentsEndIndexforRange:(NSRange)aRangeParameters
startIndexUpon return, contains the index of the first character of the paragraph containing the beginning of
aRange. PassNULLif you do not need this value (in which case the work to compute the value isn’t performed).endIndexUpon return, contains the index of the first character past the terminator of the paragraph containing the end of
aRange. PassNULLif you do not need this value (in which case the work to compute the value isn’t performed).contentsEndIndexUpon return, contains the index of the first character of the terminator of the paragraph containing the end of
aRange. PassNULLif you do not need this value (in which case the work to compute the value isn’t performed).aRangeA range within the receiver. The value must not exceed the bounds of the receiver.
Discussion
If
aRangeis contained with a single paragraph, of course, the returned indexes all belong to that paragraph. Similar togetLineStart:end:contentsEnd:forRange:, you can use the results of this method to construct the ranges for paragraphs.Availability
Available in OS X v10.3 and later.
See Also
-
Returns the range of characters representing the paragraph or paragraphs containing a given range.
Declaration
Parameters
aRangeA range within the receiver. The range must not exceed the bounds of the receiver.
Return Value
The range of characters representing the paragraph or paragraphs containing
aRange, including the paragraph termination characters.Availability
Available in OS X v10.3 and later.
-
Returns the range in the receiver of the composed character sequence located at a given index.
Declaration
Objective-C
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndexParameters
anIndexThe index of a character in the receiver. The value must not exceed the bounds of the receiver.
Return Value
The range in the receiver of the composed character sequence located at
anIndex.Discussion
The composed character sequence includes the first decomposed base letter found at or before
anIndex, and its length includes the decomposed base letter and all combining characters that follow.Availability
Available in OS X v10.0 and later.
-
Returns the range in the string of the composed character sequences for a given range.
Declaration
Parameters
rangeA range in the receiver. The range must not exceed the bounds of the receiver.
Return Value
The range in the receiver that includes the composed character sequences in
range.Discussion
This method provides a convenient way to grow a range to include all composed character sequences it overlaps.
Availability
Available in OS X v10.5 and later.
-
Parses the receiver as a text representation of a property list, returning an
NSString,NSData,NSArray, orNSDictionaryobject, according to the topmost element.Return Value
A property list representation of returning an
NSString,NSData,NSArray, orNSDictionaryobject, according to the topmost element.Discussion
The receiver must contain a string in a property list format. For a discussion of property list formats, see Property List Programming Guide.
Availability
Available in OS X v10.0 and later.
-
Returns a dictionary object initialized with the keys and values found in the receiver.
Declaration
Objective-C
- (NSDictionary *)propertyListFromStringsFileFormatReturn Value
A dictionary object initialized with the keys and values found in the receiver
Discussion
The receiver must contain text in the format used for
.stringsfiles. In this format, keys and values are separated by an equal sign, and each key-value pair is terminated with a semicolon. The value is optional—if not present, the equal sign is also omitted. The keys and values themselves are always strings enclosed in straight quotation marks. Comments may be included, delimited by/*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";
Availability
Available in OS X v10.0 and later.
-
Draws the receiver with the font and other display characteristics of the given attributes, at the specified point in the current graphics context.
Declaration
Objective-C
- (void)drawAtPoint:(NSPoint)pointwithAttributes:(NSDictionary<NSString *,id> *)attrsParameters
pointThe point in the current graphics context where you want to start drawing the string. The coordinate system of the graphics context is usually defined by the view in which you are drawing. In AppKit, the origin is normally in the lower-left corner of the drawing area, but the origin is in the upper-left corner if the focused view is flipped.
attrsA dictionary of text attributes to be applied to the string. These are the same attributes that can be applied to an
NSAttributedStringobject, but in the case ofNSStringobjects, the attributes apply to the entire string, rather than ranges within the string.Discussion
The width (height for vertical layout) of the rendering area is unlimited, unlike
drawInRect:withAttributes:, which uses a bounding rectangle. As a result, this method renders the text in a single line. However, if newline characters are present in the string, those characters are honored and cause subsequent text to be placed on the next line underneath the starting point.There must be either a focused view or an active graphics context when you call this method.
Import Statement
Objective-C
@import AppKit;Swift
import AppKitAvailability
Available in OS X v10.0 and later.
-
Draws the attributed string inside the specified bounding rectangle.
Declaration
Objective-C
- (void)drawInRect:(NSRect)rectwithAttributes:(NSDictionary<NSString *,id> *)attrsParameters
rectThe bounding rectangle in which to draw the string. In AppKit, the origin of the bounding box is normally in the lower-left corner, but the origin is in the upper-left corner if the focused view is flipped.
attrsThe text attributes with which to draw the string. These are the same attributes that can be applied to an
NSAttributedStringobject, but in the case ofNSStringobjects, the attributes apply to the entire string, rather than ranges within the string.Discussion
This method draws as much of the string as it can inside the specified rectangle, wrapping the string text as needed to make it fit. If the string is too long to fit inside the rectangle, the method renders as much as possible and clips the rest.
If newline characters are present in the string, those characters are honored and cause subsequent text to be placed on the next line underneath the starting point.
There must be either a focused view or an active graphics context when you call this method.
Import Statement
Objective-C
@import AppKit;Swift
import AppKitAvailability
Available in OS X v10.0 and later.
-
Draws the attributed string in the specified bounding rectangle using the provided options.
Declaration
Swift
func drawWithRect(_rect: NSRect, optionsoptions: NSStringDrawingOptions, attributesattributes: [String : AnyObject]?, contextcontext: NSStringDrawingContext?)Objective-C
- (void)drawWithRect:(NSRect)rectoptions:(NSStringDrawingOptions)optionsattributes:(NSDictionary<NSString *,id> *)attributescontext:(NSStringDrawingContext *)contextParameters
rectThe bounding rectangle in which to draw the string.
optionsAdditional drawing options to apply to the string during rendering. For a list of possible values, see
NSStringDrawingOptions.attributesThe text attributes with which to draw the string. These are the same attributes that can be applied to an
NSAttributedStringobject, but in the case ofNSStringobjects, the attributes apply to the entire string, rather than ranges within the string.contextA context object with information about how to adjust the font tracking and scaling information. On return, the specified object contains information about the actual values used to render the string. This parameter may be
nil.Discussion
This method draws as much of the string as it can inside the specified rectangle, wrapping the string text as needed to make it fit. If the string is too big to fit completely inside the rectangle, the method scales the font or adjusts the letter spacing to make the string fit within the given bounds.
If newline characters are present in the string, those characters are honored and cause subsequent text to be placed on the next line underneath the starting point. To correctly draw and size multi-line text, pass
NSStringDrawingUsesLineFragmentOriginin the options parameter.Special Considerations
This method uses the baseline origin by default.
If
NSStringDrawingUsesLineFragmentOriginis not specified, the rectangle’s height will be ignored and the operation considered to be single-line rendering.Import Statement
Objective-C
@import AppKit;Swift
import AppKitAvailability
Available in OS X v10.11 and later.
-
boundingRectWithSize(_:options:attributes:context:) - boundingRectWithSize:options:attributes:context:Calculates and returns the bounding rect for the receiver drawn using the given options and display characteristics, within the specified rectangle in the current graphics context.
Declaration
Swift
func boundingRectWithSize(_size: NSSize, optionsoptions: NSStringDrawingOptions, attributesattributes: [String : AnyObject]?, contextcontext: NSStringDrawingContext?) -> NSRectObjective-C
- (NSRect)boundingRectWithSize:(NSSize)sizeoptions:(NSStringDrawingOptions)optionsattributes:(NSDictionary<NSString *,id> *)attributescontext:(NSStringDrawingContext *)contextParameters
sizeThe size of the rectangle to draw in.
optionsString drawing options.
attributesA dictionary of text attributes to be applied to the string. These are the same attributes that can be applied to an
NSAttributedStringobject, but in the case ofNSStringobjects, the attributes apply to the entire string, rather than ranges within the string.contextThe string drawing context to use for the receiver, specifying minimum scale factor and tracking adjustments.
Return Value
The bounding rect for the receiver drawn using the given options and display characteristics. The rect origin returned from this method is the first glyph origin.
Discussion
To correctly draw and size multi-line text, pass
NSStringDrawingUsesLineFragmentOriginin the options parameter.This method returns fractional sizes (in the
sizecomponent of the returnedCGRect); to use a returned size to size views, you must raise its value to the nearest higher integer using theceilfunction.This method returns the actual bounds of the glyphs in the string. Some of the glyphs (spaces, for example) are allowed to overlap the layout constraints specified by the size passed in, so in some cases the width value of the size component of the returned
CGRectcan exceed the width value of thesizeparameter.Import Statement
Objective-C
@import AppKit;Swift
import AppKitAvailability
Available in OS X v10.11 and later.
See Also
-
Returns the bounding box size the receiver occupies when drawn with the given attributes.
Declaration
Objective-C
- (NSSize)sizeWithAttributes:(NSDictionary<NSString *,id> *)attrsParameters
attrsA dictionary of text attributes to be applied to the string. These are the same attributes that can be applied to an
NSAttributedStringobject, but in the case ofNSStringobjects, the attributes apply to the entire string, rather than ranges within the string.Return Value
The bounding box size the receiver occupies when drawn with the specified attributes.
Discussion
This method returns fractional sizes; to use a returned size to size views, you must raise its value to the nearest higher integer using the
ceilfunction.Import Statement
Objective-C
@import AppKit;Swift
import AppKitAvailability
Available in OS X v10.0 and later.
-
Returns a string with the given character folding options applied.
Declaration
Swift
func stringByFoldingWithOptions(_options: NSStringCompareOptions, localelocale: NSLocale?) -> StringObjective-C
- (NSString *)stringByFoldingWithOptions:(NSStringCompareOptions)optionslocale:(NSLocale *)localeParameters
optionsA mask of compare flags with a suffix
InsensitiveSearch.localeThe locale to use for the folding. To use the current locale, pass [
NSLocalecurrentLocale]. To use the system locale, passnil.Return Value
A string with the character folding options applied.
Discussion
Character folding operations remove distinctions between characters. For example, case folding may replace uppercase letters with their lowercase equivalents.
The locale affects the folding logic. For example, for the Turkish locale, case-insensitive compare matches “I” to “ı” (Unicode code point U+0131, Latin Small Dotless I), not the normal “i” character.
Availability
Available in OS X v10.5 and later.
-
Returns a string containing characters the receiver and a given string have in common, starting from the beginning of each up to the first characters that aren’t equivalent.
Declaration
Swift
func commonPrefixWithString(_str: String, optionsmask: NSStringCompareOptions) -> StringObjective-C
- (NSString *)commonPrefixWithString:(NSString *)aStringoptions:(NSStringCompareOptions)maskParameters
aStringThe string with which to compare the receiver.
maskOptions for the comparison. The following search options may be specified by combining them with the C bitwise
ORoperator:NSCaseInsensitiveSearch,NSLiteralSearch. See String Programming Guide for details on these options.Return Value
A string containing characters the receiver and
aStringhave in common, starting from the beginning of each up to the first characters that aren’t equivalent.Discussion
The returned string is based on the characters of the receiver. For example, if the receiver is “Ma¨dchen” and
aStringis “Mädchenschule”, the string returned is “Ma¨dchen”, not “Mädchen”.Availability
Available in OS X v10.0 and later.
See Also
-
capitalizedString capitalizedStringPropertyA capitalized representation of the receiver. (read-only)
Declaration
Swift
var capitalizedString: String { get }Objective-C
@property(readonly, copy) NSString *capitalizedStringDiscussion
A string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.
A “word” is any sequence of characters delimited by spaces, tabs, or line terminators (listed under
getLineStart:end:contentsEnd:forRange:). Some common word delimiting punctuation isn’t considered, so this property may not generally produce the desired results for multiword strings.Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See
lowercaseStringfor an example.Availability
Available in OS X v10.0 and later.
See Also
-
Returns a capitalized representation of the receiver using the specified locale.
Declaration
Objective-C
- (NSString *)capitalizedStringWithLocale:(NSLocale *)localeParameters
localeThe locale. For strings presented to users, pass the current locale ([
NSLocalecurrentLocale]). To use the system locale, passnil.Return Value
A string with the first character from each word in the receiver changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.
Discussion
A “word” is any sequence of characters delimited by spaces, tabs, or line terminators (listed under
getLineStart:end:contentsEnd:forRange:). Some common word delimiting punctuation isn’t considered, so this method may not generally produce the desired results for multiword strings.Availability
Available in OS X v10.8 and later.
See Also
-
lowercaseString lowercaseStringPropertyA lowercase representation of the string.
Declaration
Swift
var lowercaseString: String { get }Objective-C
@property(readonly, copy) NSString *lowercaseStringDiscussion
Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. The result of this statement:
lcString = [myString lowercaseString];
might not be equal to this statement:
lcString = [[myString uppercaseString] lowercaseString];
For example, the uppercase form of “ß” in German is “SS”, so converting “Straße” to uppercase, then lowercase, produces this sequence of strings:
“Straße”
“STRASSE”
“strasse”
Availability
Available in OS X v10.0 and later.
-
Returns a version of the string with all letters converted to lowercase, taking into account the specified locale.
Declaration
Objective-C
- (NSString *)lowercaseStringWithLocale:(NSLocale *)localeParameters
localeThe locale. For strings presented to users, pass the current locale ([
NSLocalecurrentLocale]). To use the system local, passnil.Return Value
A lowercase string using the
locale. Input of@"ABcde"would result in a return of@"abcde".Discussion
.
Availability
Available in OS X v10.8 and later.
-
uppercaseString uppercaseStringPropertyAn uppercase representation of the string. (read-only)
Declaration
Swift
var uppercaseString: String { get }Objective-C
@property(readonly, copy) NSString *uppercaseStringDiscussion
Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See
lowercaseStringfor an example.Availability
Available in OS X v10.0 and later.
-
Returns a version of the string with all letters converted to uppercase, taking into account the specified locale.
Declaration
Objective-C
- (NSString *)uppercaseStringWithLocale:(NSLocale *)localeParameters
localeThe locale. For strings presented to users, pass the current locale ([
NSLocalecurrentLocale]). To use the system locale, passnil.Return Value
An uppercase string using the
locale. Input of@"ABcde"would result in a return of@"ABCDE".Availability
Available in OS X v10.8 and later.
-
A string made by normalizing the string’s contents using the Unicode Normalization Form D. (read-only)
Declaration
Swift
var decomposedStringWithCanonicalMapping: String { get }Objective-C
@property(readonly, copy) NSString *decomposedStringWithCanonicalMappingAvailability
Available in OS X v10.2 and later.
-
A string made by normalizing the receiver’s contents using the Unicode Normalization Form KD. (read-only)
Declaration
Swift
var decomposedStringWithCompatibilityMapping: String { get }Objective-C
@property(readonly, copy) NSString *decomposedStringWithCompatibilityMappingAvailability
Available in OS X v10.2 and later.
-
A string made by normalizing the string’s contents using the Unicode Normalization Form C. (read-only)
Declaration
Swift
var precomposedStringWithCanonicalMapping: String { get }Objective-C
@property(readonly, copy) NSString *precomposedStringWithCanonicalMappingAvailability
Available in OS X v10.2 and later.
-
A string made by normalizing the receiver’s contents using the Unicode Normalization Form KC. (read-only)
Declaration
Swift
var precomposedStringWithCompatibilityMapping: String { get }Objective-C
@property(readonly, copy) NSString *precomposedStringWithCompatibilityMappingAvailability
Available in OS X v10.2 and later.
-
doubleValue doubleValuePropertyThe floating-point value of the string as a
double. (read-only)Declaration
Swift
var doubleValue: Double { get }Objective-C
@property(readonly) double doubleValueDiscussion
This property doesn’t include any whitespace at the beginning of the string. This property is
HUGE_VALor -HUGE_VALon overflow,0.0on underflow. This property is0.0if the string doesn’t begin with a valid text representation of a floating-point number.This property uses formatting information stored in the non-localized value; use an
NSScannerobject for localized scanning of numeric values from a string.Availability
Available in OS X v10.0 and later.
See Also
floatValuelongLongValueintegerValuescanDouble:(NSScanner) -
floatValue floatValuePropertyThe floating-point value of the string as a
float. (read-only)Discussion
This property doesn’t include whitespace at the beginning of the string. This property is
HUGE_VALor -HUGE_VALon overflow,0.0on underflow. This property is0.0if the string doesn’t begin with a valid text representation of a floating-point number.This method uses formatting information stored in the non-localized value; use an
NSScannerobject for localized scanning of numeric values from a string.Availability
Available in OS X v10.0 and later.
See Also
doubleValuelongLongValueintegerValuescanFloat:(NSScanner) -
The integer value of the string. (read-only)
Discussion
The integer value of the string, assuming a decimal representation and skipping whitespace at the beginning of the string. This property is
INT_MAXorINT_MINon overflow. This property is0if the string doesn’t begin with a valid decimal text representation of a number.This property uses formatting information stored in the non-localized value; use an
NSScannerobject for localized scanning of numeric values from a string.Special Considerations
On OS X v10.5 and later, use
integerValueinstead.Availability
Available in OS X v10.0 and later.
See Also
integerValuedoubleValuefloatValuescanInt:(NSScanner) -
integerValue integerValuePropertyThe
NSIntegervalue of the string. (read-only)Declaration
Swift
var integerValue: Int { get }Objective-C
@property(readonly) NSInteger integerValueDiscussion
The
NSIntegervalue of the string, assuming a decimal representation and skipping whitespace at the beginning of the string. This property is0if the string doesn’t begin with a valid decimal text representation of a number.This property uses formatting information stored in the non-localized value; use an
NSScannerobject for localized scanning of numeric values from a string.Availability
Available in OS X v10.5 and later.
See Also
doubleValuefloatValuescanInt:(NSScanner) -
longLongValue longLongValuePropertyThe
long longvalue of the string. (read-only)Declaration
Swift
var longLongValue: Int64 { get }Objective-C
@property(readonly) long long longLongValueDiscussion
The
long longvalue of the string, assuming a decimal representation and skipping whitespace at the beginning of the string. This property isLLONG_MAXorLLONG_MINon overflow. This property is0if the receiver doesn’t begin with a valid decimal text representation of a number.This property uses formatting information stored in the non-localized value; use an
NSScannerobject for localized scanning of numeric values from a string.Availability
Available in OS X v10.5 and later.
See Also
doubleValuefloatValuescanInt:(NSScanner) -
The Boolean value of the string. (read-only)
Discussion
This property is
YEStrueon encountering one of "Y", "y", "T", "t", or a digit 1-9—the method ignores any trailing characters. This property isNOfalseif the receiver doesn’t begin with a valid decimal text representation of a number.The property assumes a decimal representation and skips whitespace at the beginning of the string. It also skips initial whitespace characters, or optional -/+ sign followed by zeroes.
Availability
Available in OS X v10.5 and later.
See Also
integerValuescanInt:(NSScanner)
-
Returns a zero-terminated list of the encodings string objects support in the application’s environment.
Declaration
Swift
class func availableStringEncodings() -> UnsafePointer<UInt>Objective-C
+ (const NSStringEncoding *)availableStringEncodingsReturn Value
A zero-terminated list of the encodings string objects support in the application’s environment.
Discussion
Among the more commonly used encodings are:
See the NSStringEncoding type 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
CFStringConvertEncodingToNSStringEncodingfunction to convert them to a usable format.Availability
Available in OS X v10.0 and later.
See Also
-
Returns the C-string encoding assumed for any method accepting a C string as an argument.
Declaration
Swift
class func defaultCStringEncoding() -> UIntObjective-C
+ (NSStringEncoding)defaultCStringEncodingReturn Value
The C-string encoding assumed for any method accepting a C string as an argument.
Discussion
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
NSStringcontent—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 NSStringEncoding for a full list of supported encodings.Availability
Available in OS X v10.0 and later.
-
stringEncodingForData(_:encodingOptions:convertedString:usedLossyConversion:) + stringEncodingForData:encodingOptions:convertedString:usedLossyConversion:Returns the string encoding for the given data as detected by attempting to create a string according to the specified encoding options.
Declaration
Swift
class func stringEncodingForData(_data: NSData, encodingOptionsopts: [String : AnyObject]?, convertedStringstring: AutoreleasingUnsafeMutablePointer<NSString?>, usedLossyConversionusedLossyConversion: UnsafeMutablePointer<ObjCBool>) -> UIntObjective-C
+ (NSStringEncoding)stringEncodingForData:(NSData *)dataencodingOptions:(NSDictionary<NSString *,id> *)optsconvertedString:(NSString * _Nullable *)stringusedLossyConversion:(BOOL *)usedLossyConversionParameters
dataAn
NSDataobject containing bytes in an encoding to be determined.optsOptions to use when attempting to determine the string encoding. See String Encoding Detection Options for a full list of supported options.
stringIf a string encoding could be determined, upon return contains an
NSStringobject constructed from data using the determined string encoding.usedLossyConversionIf a string encoding could be determined, upon return contains a
BOOLvalue corresponding to whether lossy conversion was used.Return Value
An
NSStringEncodingvalue, or0if a string encoding could not be determined.Availability
Available in OS X v10.10 and later.
-
Returns a human-readable string giving the name of a given encoding.
Declaration
Objective-C
+ (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encodingParameters
encodingA string encoding.
Return Value
A human-readable string giving the name of
encodingin the current locale.Availability
Available in OS X v10.0 and later.
-
Returns a Boolean value that indicates whether the receiver can be converted to a given encoding without loss of information.
Declaration
Objective-C
- (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encodingParameters
encodingA string encoding.
Return Value
YEStrueif the receiver can be converted toencodingwithout loss of information. ReturnsNOfalseif characters would have to be changed or deleted in the process of changing encodings.Discussion
If you plan to actually convert a string, the
dataUsingEncoding:...methods returnnilon failure, so you can avoid the overhead of invoking this method yourself by simply trying to convert the string.Availability
Available in OS X v10.0 and later.
-
Returns an
NSDataobject containing a representation of the receiver encoded using a given encoding.Declaration
Objective-C
- (NSData *)dataUsingEncoding:(NSStringEncoding)encodingParameters
encodingA string encoding.
Return Value
The result of invoking
dataUsingEncoding:allowLossyConversion:withNOfalseas the second argument (that is, requiring lossless conversion).Availability
Available in OS X v10.0 and later.
-
Returns an
NSDataobject containing a representation of the receiver encoded using a given encoding.Declaration
Objective-C
- (NSData *)dataUsingEncoding:(NSStringEncoding)encodingallowLossyConversion:(BOOL)flagParameters
encodingA string encoding.
flagIf
YEStrue, then allows characters to be removed or altered in conversion.Return Value
An
NSDataobject containing a representation of the receiver encoded usingencoding. ReturnsnilifflagisNOfalseand the receiver can’t be converted without losing some information (such as accents or case).Discussion
If
flagisYEStrueand 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 fromNSUnicodeStringEncodingtoNSASCIIStringEncoding, the character ‘Á’ becomes ‘A’, losing the accent.This method creates an external representation (with a byte order marker, if necessary, to indicate endianness) to ensure that the resulting
NSDataobject can be written out to a file safely. 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.Availability
Available in OS X v10.0 and later.
-
description descriptionProperty -
fastestEncoding fastestEncodingPropertyThe fastest encoding to which the receiver may be converted without loss of information. (read-only)
Declaration
Swift
var fastestEncoding: UInt { get }Objective-C
@property(readonly) NSStringEncoding fastestEncodingDiscussion
“Fastest” applies to retrieval of characters from the string. This encoding may not be space efficient.
Availability
Available in OS X v10.0 and later.
-
smallestEncoding smallestEncodingPropertyThe smallest encoding to which the receiver can be converted without loss of information. (read-only)
Declaration
Swift
var smallestEncoding: UInt { get }Objective-C
@property(readonly) NSStringEncoding smallestEncodingDiscussion
This encoding may not be the fastest for accessing characters, but is space-efficient. This property may take some time to access.
Availability
Available in OS X v10.0 and later.
-
Returns a string built from the strings in a given array by concatenating them with a path separator between each pair.
Declaration
Objective-C
+ (NSString *)pathWithComponents:(NSArray<NSString *> *)componentsParameters
componentsAn array of
NSStringobjects representing a file path. To create an absolute path, use a slash mark (“/”) as the first component. To include a trailing path divider, use an empty string as the last component.Return Value
A string built from the strings in
componentsby concatenating them (in the order they appear in the array) with a path separator between each pair.Discussion
This method doesn’t clean up the path created; use
stringByStandardizingPathto resolve empty components, references to the parent directory, and so on.Availability
Available in OS X v10.0 and later.
See Also
-
pathComponents pathComponentsPropertyThe file-system path components of the receiver. (read-only)
Declaration
Swift
var pathComponents: [String] { get }Objective-C
@property(readonly, copy) NSArray <NSString *> *pathComponentsDiscussion
The strings in the array appear in the order they did in the receiver. If the string begins or ends with the path separator, then the first or last component, respectively, will contain the separator. Empty components (caused by consecutive path separators) are deleted. For example, this code excerpt:
NSString *path = @"tmp/scratch";NSArray *pathComponents = [path pathComponents];
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”.Note that this method only works with file paths—not, for example, string representations of URLs.
Availability
Available in OS X v10.0 and later.
-
completePathIntoString(_:caseSensitive:matchesIntoArray:filterTypes:) - completePathIntoString:caseSensitive:matchesIntoArray:filterTypes:Interprets the receiver as a path in the file system and attempts to perform filename completion, returning a numeric value that indicates whether a match was possible, and by reference the longest path that matches the receiver.
Declaration
Swift
func completePathIntoString(_outputName: AutoreleasingUnsafeMutablePointer<NSString?>, caseSensitiveflag: Bool, matchesIntoArrayoutputArray: AutoreleasingUnsafeMutablePointer<NSArray?>, filterTypesfilterTypes: [String]?) -> IntObjective-C
- (NSUInteger)completePathIntoString:(NSString * _Nonnull *)outputNamecaseSensitive:(BOOL)flagmatchesIntoArray:(NSArray<NSString *> * _Nonnull *)outputArrayfilterTypes:(NSArray<NSString *> *)filterTypesParameters
outputNameUpon return, contains the longest path that matches the receiver.
flagIf
YEStrue, the method considers case for possible completions.outputArrayUpon return, contains all matching filenames.
filterTypesAn array of
NSStringobjects specifying path extensions to consider for completion. Only paths whose extensions (not including the extension separator) match one of these strings are included inoutputArray. Passnilif you don’t want to filter the output.Return Value
0if no matches are found and1if exactly one match is found. In the case of multiple matches, returns the actual number of matching paths ifoutputArrayis provided, or simply a positive value ifoutputArrayisNULL.Discussion
You can check for the existence of matches without retrieving by passing
NULLasoutputArray.Note that this method only works with file paths (not, for example, string representations of URLs).
Availability
Available in OS X v10.0 and later.
-
A file system-specific representation of the receiver. (read-only)
Declaration
Swift
var fileSystemRepresentation: UnsafePointer<Int8> { get }Objective-C
@property(readonly) const char *fileSystemRepresentationDiscussion
The returned C string will be automatically freed just as a returned object would be released; your code should copy the representation or use
getFileSystemRepresentation:maxLength:if it needs to store the representation outside of the memory context in which the representation was created.Raises an
NSCharacterConversionExceptionif the receiver can’t be represented in the file system’s encoding. It also raises an exception if the receiver contains no characters.Note that this method only works with file paths (not, for example, string representations of URLs).
To convert a
char *path (such as you might get from a C library routine) to anNSStringobject, use thestringWithFileSystemRepresentation:length:method onNSFileManager.Availability
Available in OS X v10.0 and later.
-
Interprets the receiver as a system-independent path and fills a buffer with a C-string in a format and encoding suitable for use with file-system calls.
Declaration
Swift
func getFileSystemRepresentation(_cname: UnsafeMutablePointer<Int8>, maxLengthmax: Int) -> BoolObjective-C
- (BOOL)getFileSystemRepresentation:(char *)buffermaxLength:(NSUInteger)maxLengthParameters
bufferUpon return, contains a C-string that represent the receiver as as a system-independent path, plus the
NULLtermination byte. The size ofbuffermust be large enough to containmaxLengthbytes.maxLengthThe maximum number of bytes in the string to return in
buffer(including a terminatingNULLcharacter, which this method adds).Return Value
YEStrueifbufferis successfully filled with a file-system representation, otherwiseNOfalse(for example, ifmaxLengthwould be exceeded or if the receiver can’t be represented in the file system’s encoding).Discussion
This method operates by replacing the abstract path and extension separator characters (‘
/’ and ‘.’ respectively) with their equivalents for the operating system. If the system-specific path or extension separator appears in the abstract representation, the characters it is converted to depend on the system (unless they’re identical to the abstract separators).Note that this method only works with file paths (not, for example, string representations of URLs).
The following example illustrates the use of the
maxLengthargument. The first method invocation returns failure as the file representation of the string (@"/mach_kernel") is 12 bytes long and the value passed as themaxLengthargument (12) does not allow for the addition of aNULLtermination byte.char filenameBuffer[13];BOOL success;success = [@"/mach_kernel" getFileSystemRepresentation:filenameBuffer maxLength:12];// success == NO// Changing the length to include the NULL character does worksuccess = [@"/mach_kernel" getFileSystemRepresentation:filenameBuffer maxLength:13];// success == YES
Availability
Available in OS X v10.0 and later.
See Also
-
absolutePath absolutePathPropertyA Boolean value that indicates whether the receiver represents an absolute path. (read-only)
Declaration
Swift
var absolutePath: Bool { get }Objective-C
@property(getter=isAbsolutePath, readonly) BOOL absolutePathDiscussion
YEStrueif the receiver (if interpreted as a path) represents an absolute path, otherwiseNOfalse.See String Programming Guide for more information on paths.
Note that this method only works with file paths (not, for example, string representations of URLs). The method does not check the filesystem for the existence of the path (use
fileExistsAtPath:or similar methods inNSFileManagerfor that task).Availability
Available in OS X v10.0 and later.
-
lastPathComponent lastPathComponentPropertyThe last path component of the receiver. (read-only)
Declaration
Swift
var lastPathComponent: String { get }Objective-C
@property(readonly, copy) NSString *lastPathComponentDiscussion
Path components are alphanumeric strings delineated by the path separator (slash “/”) or the beginning or end of the path string. Multiple path separators at the end of the string are stripped.
The following table illustrates the effect of
lastPathComponenton a variety of different paths:Receiver’s String Value
String Returned
“
/tmp/scratch.tiff”“
scratch.tiff”“
/tmp/scratch”“
scratch”“
/tmp/”“
tmp”“
scratch///”“
scratch”“
/”“/”
Note that this method only works with file paths (not, for example, string representations of URLs).
Availability
Available in OS X v10.0 and later.
See Also
-
pathExtension pathExtensionPropertyThe path extension, if any, of the string as interpreted as a path. (read-only)
Declaration
Swift
var pathExtension: String { get }Objective-C
@property(readonly, copy) NSString *pathExtensionDiscussion
The path extension is the portion of the last path component which follows the final period, if there is one. The extension divider is not included. The following table illustrates the effect of
pathExtensionon a variety of different paths:Receiver’s String Value
String Returned
“
/tmp/scratch.tiff”“
tiff”“
.scratch.tiff”“
tiff”“
/tmp/scratch”“” (an empty string)
“
/tmp/”“” (an empty string)
“
/tmp/scratch..tiff”“
tiff”Note that this method only works with file paths (not, for example, string representations of URLs).
Availability
Available in OS X v10.0 and later.
See Also
-
A new string that replaces the current home directory portion of the current path with a tilde (
~) character.Declaration
Swift
var stringByAbbreviatingWithTildeInPath: String { get }Objective-C
@property(readonly, copy) NSString *stringByAbbreviatingWithTildeInPathDiscussion
A new string based on the current string object. If the new string specifies a file in the current home directory, the home directory portion of the path is replaced with a tilde (
~) character. If the string does not specify a file in the current home directory, this method returns a new string object whose path is unchanged from the path in the current string.Note that this method only works with file paths. It does not work for string representations of URLs.
For sandboxed apps in OS X, the current home directory is not the same as the user’s home directory. For a sandboxed app, the home directory is the app’s home directory. So if you specified a path of
/Users/<current_user>/file.txtfor a sandboxed app, the returned path would be unchanged from the original. However, if you specified the same path for an app not in a sandbox, this method would replace the/Users/<current_user> portion of the path with a tilde.Availability
Available in OS X v10.0 and later.
See Also
-
Returns a new string made by appending to the receiver a given string.
Declaration
Objective-C
- (NSString *)stringByAppendingPathComponent:(NSString *)aStringParameters
aStringThe path component to append to the receiver.
Return Value
A new string made by appending
aStringto the receiver, preceded if necessary by a path separator.Discussion
The following table illustrates the effect of this method on a variety of different paths, assuming that
aStringis supplied as “scratch.tiff”:Receiver’s String Value
Resulting String
“
/tmp”“
/tmp/scratch.tiff”“
/tmp/”“
/tmp/scratch.tiff”“
/”“
/scratch.tiff”“” (an empty string)
“
scratch.tiff”Note that this method only works with file paths (not, for example, string representations of URLs).
Availability
Available in OS X v10.0 and later.
-
Returns a new string made by appending to the receiver an extension separator followed by a given extension.
Declaration
Objective-C
- (NSString *)stringByAppendingPathExtension:(NSString *)extParameters
extThe extension to append to the receiver.
Return Value
A new string made by appending to the receiver an extension separator followed by
ext.Discussion
The following table illustrates the effect of this method on a variety of different paths, assuming that
extis supplied as@"tiff":Receiver’s String Value
Resulting String
“
/tmp/scratch.old”“
/tmp/scratch.old.tiff”“
/tmp/scratch.”“
/tmp/scratch..tiff”“
/tmp/”“
/tmp.tiff”“
scratch”“
scratch.tiff”Note that adding an extension to
@"/tmp/"causes the result to be@"/tmp.tiff"instead of@"/tmp/.tiff". This difference is because a file named@".tiff"is not considered to have an extension, so the string is appended to the last nonempty path component.Note that this method only works with file paths (not, for example, string representations of URLs).
Special Considerations
Prior to OS X v10.9 this method did not allow you to append file extensions to filenames starting with the tilde character (
~).Availability
Available in OS X v10.0 and later.
-
A new string made by deleting the last path component from the receiver, along with any final path separator. (read-only)
Declaration
Swift
var stringByDeletingLastPathComponent: String { get }Objective-C
@property(readonly, copy) NSString *stringByDeletingLastPathComponentDiscussion
A new string made by deleting the last path component from the receiver, along with any final path separator. If the receiver represents the root path it is returned unaltered.
The following table illustrates the effect of this method on a variety of different paths:
Receiver’s String Value
Resulting String
“
/tmp/scratch.tiff”“
/tmp”“
/tmp/lock/”“
/tmp”“
/tmp/”“
/”“
/tmp”“
/”“
/”“
/”“
scratch.tiff”“” (an empty string)
Note that this method only works with file paths (not, for example, string representations of URLs).
Availability
Available in OS X v10.0 and later.
-
A new string made by deleting the extension (if any, and only the last) from the receiver. (read-only)
Declaration
Swift
var stringByDeletingPathExtension: String { get }Objective-C
@property(readonly, copy) NSString *stringByDeletingPathExtensionDiscussion
A new string made by deleting the extension (if any, and only the last) from the receiver. Strips any trailing path separator before checking for an extension. If the receiver represents the root path, it is returned unaltered.
The following table illustrates the effect of this method on a variety of different paths:
Receiver’s String Value
Resulting String
“
/tmp/scratch.tiff”“
/tmp/scratch”“
/tmp/”“
/tmp”“
scratch.bundle/”“
scratch”“
scratch..tiff”“
scratch.”“
.tiff”“
.tiff”“
/”“
/”Note that attempting to delete an extension from
@".tiff"causes the result to be@".tiff"instead of an empty string. This difference is because a file named@".tiff"is not considered to have an extension, so nothing is deleted. Note also that this method only works with file paths (not, for example, string representations of URLs).Availability
Available in OS X v10.0 and later.
-
A new string made by expanding the initial component of the receiver to its full path value. (read-only)
Declaration
Swift
var stringByExpandingTildeInPath: String { get }Objective-C
@property(readonly, copy) NSString *stringByExpandingTildeInPathDiscussion
A new string made by expanding the initial component of the receiver, if it begins with “
~” or “~user”, to its full path value. Returns a new string matching the receiver if the receiver’s initial component can’t be expanded.Note that this method only works with file paths (not, for example, string representations of URLs).
Availability
Available in OS X v10.0 and later.
-
A new string made from the receiver by resolving all symbolic links and standardizing path. (read-only)
Declaration
Swift
var stringByResolvingSymlinksInPath: String { get }Objective-C
@property(readonly, copy) NSString *stringByResolvingSymlinksInPathDiscussion
A new string made by resolving all symbolic links, then removing extraneous path components. For absolute paths, all symbolic links are guaranteed to be removed. For relative paths, symbolic links that can’t be resolved are left unresolved in the returned string.
Returns
selfif an error occurs.Note that this method only works with file paths (not, for example, string representations of URLs).
Availability
Available in OS X v10.0 and later.
-
A new string made by removing extraneous path components from the receiver. (read-only)
Declaration
Swift
var stringByStandardizingPath: String { get }Objective-C
@property(readonly, copy) NSString *stringByStandardizingPathDiscussion
A new string made by performing the following operations:
Expanding an initial tilde expression using
stringByExpandingTildeInPath.Removing an initial component of “
/private/var/automount”, “/var/automount”, or “/private” from the path, if the result still indicates an existing file or directory (checked by consulting the file system).Reducing empty components and references to the current directory (that is, the sequences “//” and “/./”) to single path separators.
Removing a trailing slash from the last component.
For absolute paths only, resolving references to the parent directory (that is, the component “..”) to the real parent directory if possible using
stringByResolvingSymlinksInPath. For relative paths, references to the parent directory are left in place.
Returns
selfif an error occurs.Note that the path returned by this method may still have symbolic link components in it. Note also that this method only works with file paths (not, for example, string representations of URLs).
Availability
Available in OS X v10.0 and later.
-
Returns an array of strings made by separately appending to the receiver each string in in a given array.
Declaration
Parameters
pathsAn array of
NSStringobjects specifying paths to add to the receiver.Return Value
An array of
NSStringobjects made by separately appending each string inpathsto the receiver, preceded if necessary by a path separator.Discussion
Note that this method only works with file paths (not, for example, string representations of URLs). See
stringByAppendingPathComponent:for an individual example.Availability
Available in OS X v10.0 and later.
-
stringByAddingPercentEncodingWithAllowedCharacters(_:) - stringByAddingPercentEncodingWithAllowedCharacters:Returns a new string made from the receiver by replacing all characters not in the specified set with percent encoded characters.
Declaration
Swift
func stringByAddingPercentEncodingWithAllowedCharacters(_allowedCharacters: NSCharacterSet) -> String?Objective-C
- (NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharactersParameters
allowedCharactersThe characters not replaced in the string.
Return Value
Returns the encoded string, or
nilif the transformation is not possible.Discussion
UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded.
This method is intended to percent-encode an URL component or subcomponent string, NOT an entire URL string. Any characters in
allowedCharactersoutside of the 7-bit ASCII range are ignored.Availability
Available in OS X v10.9 and later.
-
Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters.
Declaration
Swift
var stringByRemovingPercentEncoding: String? { get }Objective-C
@property(readonly, copy) NSString *stringByRemovingPercentEncodingReturn Value
A new string with the percent encoded sequences removed, or
nilif the receiver contains an invalid percent-encoding sequence.Availability
Available in OS X v10.9 and later.
-
enumerateLinguisticTagsInRange(_:scheme:options:orthography:usingBlock:) - enumerateLinguisticTagsInRange:scheme:options:orthography:usingBlock:Performs linguistic analysis on the specified string by enumerating the specific range of the string, providing the Block with the located tags.
Declaration
Swift
func enumerateLinguisticTagsInRange(_range: NSRange, schemetagScheme: String, optionsopts: NSLinguisticTaggerOptions, orthographyorthography: NSOrthography?, usingBlockblock: (String, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void)Objective-C
- (void)enumerateLinguisticTagsInRange:(NSRange)rangescheme:(NSString *)tagSchemeoptions:(NSLinguisticTaggerOptions)optsorthography:(NSOrthography *)orthographyusingBlock:(void (^)(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop))blockParameters
rangeThe range of the string to analyze.
tagSchemeThe tag scheme to use. See
Linguistic Tag Schemesfor supported values.optsThe linguistic tagger options to use. See
NSLinguisticTaggerOptionsfor the constants. These constants can be combined using the C-Bitwise OR operator.orthographyThe orthography of the string. If
nil, the linguistic tagger will attempt to determine the orthography from the string content.blockThe Block to apply to the string.
The block takes four arguments:
tagThe tag scheme for the token. The opts parameter specifies the types of tagger options that are located.
tokenRangeThe range of a string matching the tag scheme.
sentenceRangeThe range of the sentence in which the token is found.
stopA reference to a Boolean value. The block can set the value to
YEStrueto stop further processing of the array. Thestopargument is an out-only argument. You should only ever set this Boolean toYEStruewithin the Block.Discussion
This is a convenience method. It is the equivalent of creating an instance of
NSLinguisticTagger, specifying the receiver as the string to be analyzed, and the orthography (ornil) and then invoking theNSLinguisticTaggermethod orenumerateTagsInRange:scheme:options:usingBlock:.Availability
Available in OS X v10.7 and later.
-
linguisticTagsInRange(_:scheme:options:orthography:tokenRanges:) - linguisticTagsInRange:scheme:options:orthography:tokenRanges:Returns an array of linguistic tags for the specified range and requested tags within the receiving string.
Declaration
Swift
func linguisticTagsInRange(_range: NSRange, schemetagScheme: String, optionsopts: NSLinguisticTaggerOptions, orthographyorthography: NSOrthography?, tokenRangestokenRanges: AutoreleasingUnsafeMutablePointer<NSArray?>) -> [String]Objective-C
- (NSArray<NSString *> *)linguisticTagsInRange:(NSRange)rangescheme:(NSString *)tagSchemeoptions:(NSLinguisticTaggerOptions)optsorthography:(NSOrthography *)orthographytokenRanges:(NSArray<NSValue *> * _Nullable *)tokenRangesParameters
rangeThe range of the string to analyze.
tagSchemeThe tag scheme to use. See
Linguistic Tag Schemesfor supported values.optsThe linguistic tagger options to use. See
NSLinguisticTaggerOptionsfor the constants. These constants can be combined using the C-Bitwise OR operator.orthographyThe orthography of the string. If
nil, the linguistic tagger will attempt to determine the orthography from the string content.tokenRangesAn array returned by-reference containing the token ranges of the linguistic tags wrapped in
NSValueobjects.Return Value
Returns an array containing the linguistic tags for the
tokenRangeswithin the receiving string.Discussion
This is a convenience method. It is the equivalent of creating an instance of
NSLinguisticTagger, specifying the receiver as the string to be analyzed, and the orthography (ornil) and then invoking theNSLinguisticTaggermethod orlinguisticTagsInRange:scheme:options:orthography:tokenRanges:.Availability
Available in OS X v10.7 and later.
-
+ stringWithCString:(OS X v10.4)Creates a new string using a given C-string.
Deprecation Statement
Use
stringWithCString:encoding:instead.Declaration
Objective-C
+ (id)stringWithCString:(const char *)bytesDiscussion
cStringshould contain data in the default C string encoding. If the argument passed tostringWithCString:is not a zero-terminated C-string, the results are undefined.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
See Also
-
- initWithCString:(OS X v10.4)Initializes the receiver, a newly allocated
NSStringobject, by converting the data in a given C-string from the default C-string encoding into the Unicode character encoding.Deprecation Statement
Use
initWithCString:encoding:instead.Declaration
Objective-C
- (id)initWithCString:(const char *)bytesDiscussion
cStringmust be a zero-terminated C string in the default C string encoding, and may not beNULL. Returns an initialized object, which might be different from the original receiver.To create an immutable string from an immutable C string buffer, do not attempt to use this method. Instead, use
initWithCStringNoCopy:length:freeWhenDone:.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
See Also
-
+ stringWithCString:length:(OS X v10.4)Returns a string containing the characters in a given C-string.
Deprecation Statement
Use
stringWithCString:encoding:instead.Declaration
Objective-C
+ (id)stringWithCString:(const char *)byteslength:(NSUInteger)lengthDiscussion
cStringmust not be NULL.cStringshould contain characters in the default C-string encoding. This method convertslength*sizeof(char)bytes fromcStringand doesn’t stop short at aNULLcharacter.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
See Also
-
- initWithCString:length:(OS X v10.4)Initializes the receiver, a newly allocated
NSStringobject, by converting the data in a given C-string from the default C-string encoding into the Unicode character encoding.Deprecation Statement
Use
initWithBytes:length:encoding:instead.Declaration
Objective-C
- (id)initWithCString:(const char *)byteslength:(NSUInteger)lengthDiscussion
This method converts
length*sizeof(char)bytes fromcStringand doesn’t stop short at a zero character.cStringmust contain bytes in the default C-string encoding and may not beNULL. Returns an initialized object, which might be different from the original receiver.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
See Also
-
- initWithCStringNoCopy:length:freeWhenDone:(OS X v10.4)Initializes the receiver, a newly allocated
NSStringobject, by converting the data in a given C-string from the default C-string encoding into the Unicode character encoding.Deprecation Statement
Use
initWithBytesNoCopy:length:encoding:freeWhenDone:instead.Declaration
Objective-C
- (id)initWithCStringNoCopy:(char *)byteslength:(NSUInteger)lengthfreeWhenDone:(BOOL)freeBufferDiscussion
This method converts
length*sizeof(char)bytes fromcStringand doesn’t stop short at a zero character.cStringmust contain data in the default C-string encoding and may not beNULL. The receiver becomes the owner ofcString; ifflagisYEStrueit will free the memory when it no longer needs it, but ifflagisNOfalseit won’t. Returns an initialized object, which might be different from the original receiver.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 thefreeWhenDoneargument toinitWithStringNoCopyisNOfalse, the C string passed as the method’s first argument cannot be modified, so you can safely useinitWithStringNoCopyto create an immutable string from an immutable (const char *) C-string buffer.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
See Also
-
+ stringWithContentsOfFile:(OS X v10.4)Returns a string created by reading data from the file named by a given path.
Deprecation Statement
Use
stringWithContentsOfFile:encoding:error:or stringWithContentsOfFile:usedEncoding:error: instead.Declaration
Objective-C
+ (id)stringWithContentsOfFile:(NSString *)pathDiscussion
If the contents begin with a Unicode byte-order mark (
U+FEFForU+FFFE), interprets the contents as UTF–16 code units. If the contents begin with a UTF-8 byte-order mark (EFBBBF), interprets the contents as UTF-8. Otherwise, interprets the contents as data in the default C string encoding. Since the default C string encoding will vary with the user’s configuration, do not depend on this method unless you are using Unicode or UTF-8 or you can verify the default C string encoding. Returnsnilif the file can’t be opened.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
-
- initWithContentsOfFile:(OS X v10.4)Initializes the receiver, a newly allocated
NSStringobject, by reading data from the file named bypath.Deprecation Statement
Use
initWithContentsOfFile:encoding:error:orinitWithContentsOfFile:usedEncoding:error:instead.Declaration
Objective-C
- (id)initWithContentsOfFile:(NSString *)pathDiscussion
Initializes the receiver, a newly allocated
NSStringobject, by reading data from the file named bypath. If the contents begin with a byte-order mark (U+FEFForU+FFFE), interprets the contents as UTF–16 code units; otherwise interprets the contents as data in the default C string encoding. Returns an initialized object, which might be different from the original receiver, ornilif the file can’t be opened.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
-
+ stringWithContentsOfURL:(OS X v10.4)Returns a string created by reading data from the file named by a given URL.
Deprecation Statement
Use
stringWithContentsOfURL:encoding:error:orstringWithContentsOfURL:usedEncoding:error:instead.Declaration
Objective-C
+ (id)stringWithContentsOfURL:(NSURL *)urlDiscussion
If the contents begin with a byte-order mark (U+FEFF or U+FFFE), interprets the contents as UTF–16 code units. If the contents begin with a UTF-8 byte-order mark (EFBBBF), interprets the contents as UTF-8. Otherwise interprets the contents as data in the default C string encoding. Since the default C string encoding will vary with the user’s configuration, do not depend on this method unless you are using Unicode or UTF-8 or you can verify the default C string encoding. Returns
nilif the location can’t be opened.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
-
- initWithContentsOfURL:(OS X v10.4)Initializes the receiver, a newly allocated
NSStringobject, by reading data from the location named by a given URL.Deprecation Statement
Use
initWithContentsOfURL:encoding:error:orinitWithContentsOfURL:usedEncoding:error:instead.Declaration
Objective-C
- (id)initWithContentsOfURL:(NSURL *)urlDiscussion
Initializes the receiver, a newly allocated
NSStringobject, by reading data from the location named byaURL. If the contents begin with a byte-order mark (U+FEFForU+FFFE), interprets the contents as UTF–16 code units; otherwise interprets the contents as data in the default C string encoding. Returns an initialized object, which might be different from the original receiver, ornilif the location can’t be opened.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
-
- writeToFile:atomically:(OS X v10.4)Writes the contents of the receiver to the file specified by a given path.
Deprecation Statement
Use
writeToFile:atomically:encoding:error:instead.Declaration
Objective-C
- (BOOL)writeToFile:(NSString *)pathatomically:(BOOL)useAuxiliaryFileReturn Value
YEStrueif the file is written successfully, otherwiseNOfalse.Discussion
Writes the contents of the receiver to the file specified by
path(overwriting any existing file atpath).pathis written in the default C-string encoding if possible (that is, if no information would be lost), in the Unicode encoding otherwise.If
flagisYEStrue, the receiver is written to an auxiliary file, and then the auxiliary file is renamed topath. IfflagisNOfalse, the receiver is written directly topath. TheYEStrueoption guarantees thatpath, if it exists at all, won’t be corrupted even if the system should crash during writing.If
pathcontains a tilde (~) character, you must expand it withstringByExpandingTildeInPathbefore invoking this method.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
-
- writeToURL:atomically:(OS X v10.4)Writes the contents of the receiver to the location specified by a given URL.
Deprecation Statement
Use
writeToURL:atomically:encoding:error:instead.Declaration
Objective-C
- (BOOL)writeToURL:(NSURL *)urlatomically:(BOOL)atomicallyReturn Value
YEStrueif the location is written successfully, otherwiseNOfalse.Discussion
If
atomicallyisYEStrue, the receiver is written to an auxiliary location, and then the auxiliary location is renamed toaURL. IfatomicallyisNOfalse, the receiver is written directly toaURL. TheYEStrueoption guarantees thataURL, if it exists at all, won’t be corrupted even if the system should crash during writing.The
atomicallyparameter is ignored ifaURLis not of a type that can be accessed atomically.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
-
getCharacters(_:) - getCharacters:(OS X v10.6)Copies all characters from the receiver into a given buffer.
Deprecation Statement
This method is unsafe because it could potentially cause buffer overruns. Use
getCharacters:range:instead.Declaration
Swift
func getCharacters(_buffer: UnsafeMutablePointer<unichar>)Objective-C
- (void)getCharacters:(unichar *)bufferParameters
bufferUpon return, contains the characters from the receiver.
buffermust be large enough to contain all characters in the string ([string length]*sizeof(unichar)).Discussion
Invokes
getCharacters:range:withbufferand the entire extent of the receiver as the range.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.6.
See Also
-
- cString(OS X v10.4)Returns a representation of the receiver as a C string in the default C-string encoding.
Deprecation Statement
Use
cStringUsingEncoding:orUTF8Stringinstead.Declaration
Objective-C
- (const char *)cStringDiscussion
The returned C string will be automatically freed just as a returned object would be released; your code should copy the C string or use
getCString:if it needs to store the C string outside of the autorelease context in which the C string is created.Raises an
NSCharacterConversionExceptionif the receiver can’t be represented in the default C-string encoding without loss of information. UsecanBeConvertedToEncoding:if necessary to check whether a string can be losslessly converted to the default C-string encoding. If it can’t, uselossyCStringordataUsingEncoding:allowLossyConversion:to get a C-string representation with some loss of information.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
-
- lossyCString(OS X v10.4)Returns a representation of the receiver as a C string in the default C-string encoding, possibly losing information in converting to that encoding.
Deprecation Statement
Use cStringUsingEncoding: or
dataUsingEncoding:allowLossyConversion:instead.Declaration
Objective-C
- (const char *)lossyCStringDiscussion
This method does not raise an exception if the conversion is lossy. The returned C string will be automatically freed just as a returned object would be released; your code should copy the C string or use
getCString:if it needs to store the C string outside of the autorelease context in which the C string is created.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
-
- cStringLength(OS X v10.4)Returns the length in char-sized units of the receiver’s C-string representation in the default C-string encoding.
Deprecation Statement
Use lengthOfBytesUsingEncoding: or maximumLengthOfBytesUsingEncoding: instead.
Declaration
Objective-C
- (NSUInteger)cStringLengthDiscussion
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, uselossyCStringto get a C-string representation with some loss of information, then check its length explicitly using the ANSI functionstrlen().Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
-
- getCString:(OS X v10.4)Invokes
getCString:maxLength:range:remainingRange:withNSMaximumStringLengthas the maximum length, the receiver’s entire extent as the range, andNULLfor the remaining range.Deprecation Statement
Use cStringUsingEncoding: or
dataUsingEncoding:allowLossyConversion:instead.Declaration
Objective-C
- (void)getCString:(char *)bytesDiscussion
buffermust be large enough to contain the resulting C-string plus a terminating NULL character (which this method adds—[string cStringLength]).Raises an
NSCharacterConversionExceptionif the receiver can’t be represented in the default C-string encoding without loss of information. UsecanBeConvertedToEncoding:if necessary to check whether a string can be losslessly converted to the default C-string encoding. If it can’t, uselossyCStringordataUsingEncoding:allowLossyConversion:to get a C-string representation with some loss of information.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
-
- getCString:maxLength:(OS X v10.4)Invokes
getCString:maxLength:range:remainingRange:withmaxLengthas the maximum length in char-sized units, the receiver’s entire extent as the range, andNULLfor the remaining range.Deprecation Statement
Use getCString:maxLength:encoding: instead.
Declaration
Objective-C
- (void)getCString:(char *)bytesmaxLength:(NSUInteger)maxLengthDiscussion
buffermust be large enough to containmaxLengthchars plus a terminating zero char (which this method adds).Raises an
NSCharacterConversionExceptionif the receiver can’t be represented in the default C-string encoding without loss of information. UsecanBeConvertedToEncoding:if necessary to check whether a string can be losslessly converted to the default C-string encoding. If it can’t, uselossyCStringordataUsingEncoding:allowLossyConversion:to get a C-string representation with some loss of information.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
-
- getCString:maxLength:range:remainingRange:(OS X v10.4)Converts the receiver’s content to the default C-string encoding and stores them in a given buffer.
Deprecation Statement
Use getCString:maxLength:encoding: instead.
Declaration
Objective-C
- (void)getCString:(char *)bytesmaxLength:(NSUInteger)maxLengthrange:(NSRange)aRangeremainingRange:(NSRangePointer)leftoverRangeDiscussion
buffermust be large enough to containmaxLengthbytes plus a terminating zero character (which this method adds). Copies and converts as many characters as possible fromaRangeand stores the range of those not converted in the range given byleftoverRange(if it’s non-nil). Raises anNSRangeExceptionif any part ofaRangelies beyond the end of the string.Raises an
NSCharacterConversionExceptionif the receiver can’t be represented in the default C-string encoding without loss of information. UsecanBeConvertedToEncoding:if necessary to check whether a string can be losslessly converted to the default C-string encoding. If it can’t, uselossyCStringordataUsingEncoding:allowLossyConversion:to get a C-string representation with some loss of information.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.4.
-
stringByAddingPercentEscapesUsingEncoding(_:) - stringByAddingPercentEscapesUsingEncoding:(OS X v10.11)Returns a representation of the receiver using a given encoding to determine the percent escapes necessary to convert the receiver into a legal URL string.
Deprecation Statement
Use
stringByAddingPercentEncodingWithAllowedCharacters:instead.Declaration
Objective-C
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encodingParameters
encodingThe encoding to use for the returned string. If you are uncertain of the correct encoding you should use
NSUTF8StringEncoding.Return Value
A representation of the receiver using
encodingto determine the percent escapes necessary to convert the receiver into a legal URL string. Returnsnilifencodingcannot encode a particular character.Discussion
It may be difficult to use this function to "clean up" unescaped or partially escaped URL strings where sequences are unpredictable. See
CFURLCreateStringByAddingPercentEscapesfor more information.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.11.
-
stringByReplacingPercentEscapesUsingEncoding(_:) - stringByReplacingPercentEscapesUsingEncoding:(OS X v10.11)Returns a new string made by replacing in the receiver all percent escapes with the matching characters as determined by a given encoding.
Use
stringByRemovingPercentEncodinginstead.Declaration
Objective-C
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encodingParameters
encodingThe encoding to use for the returned string.
Return Value
A new string made by replacing in the receiver all percent escapes with the matching characters as determined by the given encoding
encoding. Returnsnilif the transformation is not possible, for example, the percent escapes give a byte sequence not legal inencoding.Discussion
See
CFURLCreateStringByReplacingPercentEscapesfor more complex transformations.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.11.
-
Draws the receiver with the specified options and other display characteristics of the given attributes, within the specified rectangle in the current graphics context.
Declaration
Swift
func drawWithRect(_rect: NSRect, optionsoptions: NSStringDrawingOptions, attributesattributes: [String : AnyObject]?)Objective-C
- (void)drawWithRect:(NSRect)rectoptions:(NSStringDrawingOptions)optionsattributes:(NSDictionary<NSString *,id> *)attributesParameters
rectThe rectangle in which to draw the string.
optionsString drawing options.
attributesA dictionary of text attributes to be applied to the string. These are the same attributes that can be applied to an
NSAttributedStringobject, but in the case ofNSStringobjects, the attributes apply to the entire string, rather than ranges within the string.Discussion
This method works in single-line, baseline rendering configuration by default. That is, the
rectargument'soriginfield specifies the rendering origin, and that point is interpreted as the baseline origin by default. If the string drawing optionNSStringDrawingUsesLineFragmentOriginis specified,originis interpreted as the upper left corner of the line fragment rectangle, and the method behaves in multiline configuration.The
sizefield specifies the text container size. Thewidthpart of the size field specifies the maximum line fragment width if larger than0.0. Theheightdefines the maximum size that can be occupied with text if larger than0.0andNSStringDrawingUsesLineFragmentOriginis specified. IfNSStringDrawingUsesLineFragmentOriginis not specified, height is ignored and considered to be single-line rendering (NSLineBreakByWordWrappingandNSLineBreakByCharWrappingare treated asNSLineBreakByClipping).You should only invoke this method when there is a current graphics context.
Import Statement
Objective-C
@import AppKit;Swift
import AppKitAvailability
Available in OS X v10.4 and later.
Deprecated in OS X v10.11.
-
boundingRectWithSize(_:options:attributes:) - boundingRectWithSize:options:attributes:(OS X v10.11)Calculates and returns the bounding rect for the receiver drawn using the given options and display characteristics, within the specified rectangle in the current graphics context.
Declaration
Swift
func boundingRectWithSize(_size: NSSize, optionsoptions: NSStringDrawingOptions, attributesattributes: [String : AnyObject]?) -> NSRectObjective-C
- (NSRect)boundingRectWithSize:(NSSize)sizeoptions:(NSStringDrawingOptions)optionsattributes:(NSDictionary<NSString *,id> *)attributesParameters
sizeThe size of the rectangle to draw in.
optionsString drawing options.
attributesA dictionary of text attributes to be applied to the string. These are the same attributes that can be applied to an
NSAttributedStringobject, but in the case ofNSStringobjects, the attributes apply to the entire string, rather than ranges within the string.Return Value
The bounding rect for the receiver drawn using the given options and display characteristics. The rect origin returned from this method is the first glyph origin.
Special Considerations
This method works in single-line, baseline rendering configuration by default. If the string drawing option
NSStringDrawingUsesLineFragmentOriginis specified, the method behaves in multiline configuration.Import Statement
Objective-C
@import AppKit;Swift
import AppKitAvailability
Available in OS X v10.4 and later.
Deprecated in OS X v10.11.
Data Types
-
Type for UTF-16 code units.
Import Statement
Objective-C
@import Foundation;Swift
import FoundationAvailability
Available in OS X v10.0 and later.
-
These values represent the options available to many of the string classes’ search and comparison methods.
Declaration
Swift
struct NSStringCompareOptions : OptionSetType { init(rawValuerawValue: UInt) static var CaseInsensitiveSearch: NSStringCompareOptions { get } static var LiteralSearch: NSStringCompareOptions { get } static var BackwardsSearch: NSStringCompareOptions { get } static var AnchoredSearch: NSStringCompareOptions { get } static var NumericSearch: NSStringCompareOptions { get } static var DiacriticInsensitiveSearch: NSStringCompareOptions { get } static var WidthInsensitiveSearch: NSStringCompareOptions { get } static var ForcedOrderingSearch: NSStringCompareOptions { get } static var RegularExpressionSearch: NSStringCompareOptions { get } }Objective-C
typedef enum NSStringCompareOptions : NSUInteger { NSCaseInsensitiveSearch = 1, NSLiteralSearch = 2, NSBackwardsSearch = 4, NSAnchoredSearch = 8, NSNumericSearch = 64, NSDiacriticInsensitiveSearch = 128, NSWidthInsensitiveSearch = 256, NSForcedOrderingSearch = 512, NSRegularExpressionSearch = 1024 } NSStringCompareOptions;Constants
-
CaseInsensitiveSearchNSCaseInsensitiveSearchA case-insensitive search.
Available in OS X v10.0 and later.
-
LiteralSearchNSLiteralSearchExact character-by-character equivalence.
Available in OS X v10.0 and later.
-
BackwardsSearchNSBackwardsSearchSearch from end of source string.
Available in OS X v10.0 and later.
-
AnchoredSearchNSAnchoredSearchSearch is limited to start (or end, if
NSBackwardsSearch) of source string.Available in OS X v10.0 and later.
-
NumericSearchNSNumericSearchNumbers within strings are compared using numeric value, that is,
Name2.txt<Name7.txt<Name25.txt.Numeric comparison only applies to the numerals in the string, not other characters that would have meaning in a true number such as a negative sign or a decimal point.
This option only applies to compare methods, not find.
Available in OS X v10.3 and later.
-
DiacriticInsensitiveSearchNSDiacriticInsensitiveSearchSearch ignores diacritic marks.
For example, ‘ö’ is equal to ‘o’.
Available in OS X v10.5 and later.
-
WidthInsensitiveSearchNSWidthInsensitiveSearchSearch ignores width differences in characters that have full-width and half-width forms, as occurs in East Asian character sets.
For example, with this option, the full-width Latin small letter 'a' (Unicode code point U+FF41) is equal to the basic Latin small letter 'a' (Unicode code point U+0061).
Available in OS X v10.5 and later.
-
ForcedOrderingSearchNSForcedOrderingSearchComparisons are forced to return either
NSOrderedAscendingorNSOrderedDescendingif the strings are equivalent but not strictly equal.This option ensures reliable, reproducible results when sorting. For example, “aaa” is greater than "AAA” if
NSCaseInsensitiveSearchis specified.Available in OS X v10.5 and later.
-
RegularExpressionSearchNSRegularExpressionSearchThe search string is treated as an ICU-compatible regular expression. If set, no other options can apply except
NSCaseInsensitiveSearchandNSAnchoredSearch. You can use this option only with therangeOfString:...methods andstringByReplacingOccurrencesOfString:withString:options:range:.Available in OS X v10.7 and later.
Discussion
See Searching, Comparing, and Sorting Strings for details on the effects of these options.
Import Statement
Objective-C
@import Foundation;Swift
import FoundationAvailability
Available in OS X v10.5 and later.
-
-
Options for converting string encodings.
Declaration
Swift
struct NSStringEncodingConversionOptions : OptionSetType { init(rawValuerawValue: UInt) static var AllowLossy: NSStringEncodingConversionOptions { get } static var ExternalRepresentation: NSStringEncodingConversionOptions { get } }Objective-C
typedef enum NSStringEncodingConversionOptions : NSUInteger { NSStringEncodingConversionAllowLossy = 1, NSStringEncodingConversionExternalRepresentation = 2 } NSStringEncodingConversionOptions;Constants
-
AllowLossyNSStringEncodingConversionAllowLossyAllows lossy conversion.
Available in OS X v10.5 and later.
-
ExternalRepresentationNSStringEncodingConversionExternalRepresentationSpecifies an external representation (with a byte-order mark, if necessary, to indicate endianness).
Available in OS X v10.5 and later.
Import Statement
Objective-C
@import Foundation;Swift
import FoundationAvailability
Available in OS X v10.5 and later.
-
-
The following constants are provided by
NSStringas possible string encodings.Declaration
Objective-C
enum { NSASCIIStringEncoding = 1, NSNEXTSTEPStringEncoding = 2, NSJapaneseEUCStringEncoding = 3, NSUTF8StringEncoding = 4, NSISOLatin1StringEncoding = 5, NSSymbolStringEncoding = 6, NSNonLossyASCIIStringEncoding = 7, NSShiftJISStringEncoding = 8, NSISOLatin2StringEncoding = 9, NSUnicodeStringEncoding = 10, NSWindowsCP1251StringEncoding = 11, NSWindowsCP1252StringEncoding = 12, NSWindowsCP1253StringEncoding = 13, NSWindowsCP1254StringEncoding = 14, NSWindowsCP1250StringEncoding = 15, NSISO2022JPStringEncoding = 21, NSMacOSRomanStringEncoding = 30, NSUTF16StringEncoding = NSUnicodeStringEncoding, NSUTF16BigEndianStringEncoding = 0x90000100, NSUTF16LittleEndianStringEncoding = 0x94000100, NSUTF32StringEncoding = 0x8c000100, NSUTF32BigEndianStringEncoding = 0x98000100, NSUTF32LittleEndianStringEncoding = 0x9c000100, NSProprietaryStringEncoding = 65536 }; typedef NSUInteger NSStringEncoding;Constants
-
NSASCIIStringEncodingNSASCIIStringEncodingStrict 7-bit ASCII encoding within 8-bit chars; ASCII values 0…127 only.
Available in OS X v10.0 and later.
-
NSNEXTSTEPStringEncodingNSNEXTSTEPStringEncoding8-bit ASCII encoding with NEXTSTEP extensions.
Available in OS X v10.0 and later.
-
NSJapaneseEUCStringEncodingNSJapaneseEUCStringEncoding8-bit EUC encoding for Japanese text.
Available in OS X v10.0 and later.
-
NSUTF8StringEncodingNSUTF8StringEncodingAn 8-bit representation of Unicode characters, suitable for transmission or storage by ASCII-based systems.
Available in OS X v10.0 and later.
-
NSISOLatin1StringEncodingNSISOLatin1StringEncoding8-bit ISO Latin 1 encoding.
Available in OS X v10.0 and later.
-
NSSymbolStringEncodingNSSymbolStringEncoding8-bit Adobe Symbol encoding vector.
Available in OS X v10.0 and later.
-
NSNonLossyASCIIStringEncodingNSNonLossyASCIIStringEncoding7-bit verbose ASCII to represent all Unicode characters.
Available in OS X v10.0 and later.
-
NSShiftJISStringEncodingNSShiftJISStringEncoding8-bit Shift-JIS encoding for Japanese text.
Available in OS X v10.0 and later.
-
NSISOLatin2StringEncodingNSISOLatin2StringEncoding8-bit ISO Latin 2 encoding.
Available in OS X v10.0 and later.
-
NSUnicodeStringEncodingNSUnicodeStringEncodingThe canonical Unicode encoding for string objects.
Available in OS X v10.0 and later.
-
NSWindowsCP1251StringEncodingNSWindowsCP1251StringEncodingMicrosoft Windows codepage 1251, encoding Cyrillic characters; equivalent to AdobeStandardCyrillic font encoding.
Available in OS X v10.0 and later.
-
NSWindowsCP1252StringEncodingNSWindowsCP1252StringEncodingMicrosoft Windows codepage 1252; equivalent to WinLatin1.
Available in OS X v10.0 and later.
-
NSWindowsCP1253StringEncodingNSWindowsCP1253StringEncodingMicrosoft Windows codepage 1253, encoding Greek characters.
Available in OS X v10.0 and later.
-
NSWindowsCP1254StringEncodingNSWindowsCP1254StringEncodingMicrosoft Windows codepage 1254, encoding Turkish characters.
Available in OS X v10.0 and later.
-
NSWindowsCP1250StringEncodingNSWindowsCP1250StringEncodingMicrosoft Windows codepage 1250; equivalent to WinLatin2.
Available in OS X v10.0 and later.
-
NSISO2022JPStringEncodingNSISO2022JPStringEncodingISO 2022 Japanese encoding for email.
Available in OS X v10.0 and later.
-
NSMacOSRomanStringEncodingNSMacOSRomanStringEncodingClassic Macintosh Roman encoding.
Available in OS X v10.0 and later.
-
NSUTF16StringEncodingNSUTF16StringEncodingAn alias for
NSUnicodeStringEncoding.Available in OS X v10.5 and later.
-
NSUTF16BigEndianStringEncodingNSUTF16BigEndianStringEncodingNSUTF16StringEncodingencoding with explicit endianness specified.Available in OS X v10.5 and later.
-
NSUTF16LittleEndianStringEncodingNSUTF16LittleEndianStringEncodingNSUTF16StringEncodingencoding with explicit endianness specified.Available in OS X v10.5 and later.
-
NSUTF32StringEncodingNSUTF32StringEncoding32-bit UTF encoding.
Available in OS X v10.5 and later.
-
NSUTF32BigEndianStringEncodingNSUTF32BigEndianStringEncodingNSUTF32StringEncodingencoding with explicit endianness specified.Available in OS X v10.5 and later.
-
NSUTF32LittleEndianStringEncodingNSUTF32LittleEndianStringEncodingNSUTF32StringEncodingencoding with explicit endianness specified.Available in OS X v10.5 and later.
-
NSProprietaryStringEncodingNSProprietaryStringEncodingInstallation-specific encoding.
This encoding has been deprecated—there is no replacement.
Proprietary encodings have not been used since OS X v10.0. You should specify a standard encoding instead.
Available in OS X v10.7 and later.
Discussion
These values represent the various character encodings supported by the
NSStringclasses. This is an incomplete list. Additional encodings are defined in String Programming Guide for Core Foundation (seeCFStringEncodingExt.h); these encodings can be used withNSStringby first passing the Core Foundation encoding to theCFStringConvertEncodingToNSStringEncodingfunction.Import Statement
Objective-C
@import Foundation;Availability
Available in OS X v10.0 and later.
-
-
Constants to specify kinds of substrings and styles of enumeration.
Declaration
Swift
struct NSStringEnumerationOptions : OptionSetType { init(rawValuerawValue: UInt) static var ByLines: NSStringEnumerationOptions { get } static var ByParagraphs: NSStringEnumerationOptions { get } static var ByComposedCharacterSequences: NSStringEnumerationOptions { get } static var ByWords: NSStringEnumerationOptions { get } static var BySentences: NSStringEnumerationOptions { get } static var Reverse: NSStringEnumerationOptions { get } static var SubstringNotRequired: NSStringEnumerationOptions { get } static var Localized: NSStringEnumerationOptions { get } }Objective-C
typedef enum NSStringEnumerationOptions : NSUInteger { NSStringEnumerationByLines = 0, NSStringEnumerationByParagraphs = 1, NSStringEnumerationByComposedCharacterSequences = 2, NSStringEnumerationByWords = 3, NSStringEnumerationBySentences = 4, NSStringEnumerationReverse = 1UL << 8, NSStringEnumerationSubstringNotRequired = 1UL << 9, NSStringEnumerationLocalized = 1UL << 10 } NSStringEnumerationOptions;Constants
-
ByLinesNSStringEnumerationByLinesEnumerates by lines. Equivalent to
lineRangeForRange:.Available in OS X v10.6 and later.
-
ByParagraphsNSStringEnumerationByParagraphsEnumerates by paragraphs. Equivalent to
paragraphRangeForRange:.Available in OS X v10.6 and later.
-
ByComposedCharacterSequencesNSStringEnumerationByComposedCharacterSequencesEnumerates by composed character sequences. Equivalent to
rangeOfComposedCharacterSequencesForRange:.Available in OS X v10.6 and later.
-
ByWordsNSStringEnumerationByWordsEnumerates by words.
Available in OS X v10.6 and later.
-
BySentencesNSStringEnumerationBySentencesEnumerates by sentences.
Available in OS X v10.6 and later.
-
ReverseNSStringEnumerationReverseCauses enumeration to occur from the end of the specified range to the start.
Available in OS X v10.6 and later.
-
SubstringNotRequiredNSStringEnumerationSubstringNotRequiredA way to indicate that the block does not need substring, in which case
nilwill be passed. This is simply a performance shortcut.Available in OS X v10.6 and later.
-
LocalizedNSStringEnumerationLocalizedCauses the enumeration to occur using the current locale. This does not make a difference in line, paragraph, or composed character sequence enumeration, but it may for words or sentences.
Available in OS X v10.6 and later.
Discussion
These options are used with the
enumerateSubstringsInRange:options:usingBlock:method. Pass in oneNSStringEnumerationBy...option and combine with any of the remaining enumeration style constants using the C bitwiseORoperator.Import Statement
Objective-C
@import Foundation;Swift
import FoundationAvailability
Available in OS X v10.6 and later.
-
-
The following constants are provided as rendering options for a string when it is drawn.
Declaration
Swift
struct NSStringDrawingOptions : OptionSetType { init(rawValuerawValue: Int) static var UsesLineFragmentOrigin: NSStringDrawingOptions { get } static var UsesFontLeading: NSStringDrawingOptions { get } static var UsesDeviceMetrics: NSStringDrawingOptions { get } static var TruncatesLastVisibleLine: NSStringDrawingOptions { get } static var DisableScreenFontSubstitution: NSStringDrawingOptions { get } static var OneShot: NSStringDrawingOptions { get } }Objective-C
typedef enum NSStringDrawingOptions : NSInteger { NSStringDrawingUsesLineFragmentOrigin = (1 << 0), NSStringDrawingUsesFontLeading = (1 << 1), NSStringDrawingDisableScreenFontSubstitution = (1 << 2), NSStringDrawingUsesDeviceMetrics = (1 << 3), NSStringDrawingOneShot = (1 << 4), NSStringDrawingTruncatesLastVisibleLine = (1 << 5) } NSStringDrawingOptions;Constants
-
UsesLineFragmentOriginNSStringDrawingUsesLineFragmentOriginThe specified origin is the line fragment origin, not the baseline origin.
Available in OS X v10.0 and later.
-
UsesFontLeadingNSStringDrawingUsesFontLeadingUses the font leading for calculating line heights.
Available in OS X v10.0 and later.
-
DisableScreenFontSubstitutionNSStringDrawingDisableScreenFontSubstitutionDisable screen font substitution (equivalent to
[NSLayoutManager setUsesScreenFonts:NO]).Available in OS X v10.0 and later.
Deprecated in OS X v10.11.
-
UsesDeviceMetricsNSStringDrawingUsesDeviceMetricsUses image glyph bounds instead of typographic bounds.
Available in OS X v10.0 and later.
-
OneShotNSStringDrawingOneShotSuppresses caching layout information.
Available in OS X v10.0 and later.
Deprecated in OS X v10.11.
-
TruncatesLastVisibleLineNSStringDrawingTruncatesLastVisibleLineTruncates and adds the ellipsis character to the last visible line if the text doesn't fit into the bounds specified.
This option is ignored if
NSStringDrawingUsesLineFragmentOriginis not also set. In addition, the line break mode must be eitherNSLineBreakByWordWrappingorNSLineBreakByCharWrappingfor this option to take effect. The line break mode can be specified in a paragraph style passed in the attributes dictionary argument of the drawing methods.Available in OS X v10.5 and later.
Import Statement
Objective-C
@import AppKit;Swift
import AppKitAvailability
Available in OS X v10.4 and later.
-
-
Options for aligning text horizontally.
Declaration
Swift
enum NSTextAlignment : UInt { case Left case Right case Center case Justified case Natural }Objective-C
typedef enum NSTextAlignment : NSUInteger { NSTextAlignmentLeft = 0, NSTextAlignmentCenter = 1, NSTextAlignmentRight = 2, NSTextAlignmentJustified = 3, NSTextAlignmentNatural = 4, } NSTextAlignment;Constants
-
LeftNSTextAlignmentLeftAlign text along the left edge.
Available in OS X v10.11 and later.
-
CenterNSTextAlignmentCenterAlign text equally along both sides of the center line.
Available in OS X v10.11 and later.
-
RightNSTextAlignmentRightAlign text along the right edge.
Available in OS X v10.11 and later.
-
JustifiedNSTextAlignmentJustifiedFully justify the text so that the last line in a paragraph is natural aligned.
Available in OS X v10.11 and later.
-
NaturalNSTextAlignmentNaturalUse the default alignment associated with the current localization of the app. The default alignment for left-to-right scripts is
NSTextAlignmentLeft, and the default alignment for right-to-left scripts isNSTextAlignmentRight.Available in OS X v10.11 and later.
Import Statement
Objective-C
@import AppKit;Swift
import AppKitAvailability
Available in OS X v10.0 and later.
-
-
Constants for specifying the writing direction to use.
Declaration
Swift
enum NSWritingDirection : Int { case Natural case LeftToRight case RightToLeft }Objective-C
typedef enum NSWritingDirection : NSInteger { NSWritingDirectionNatural = -1, NSWritingDirectionLeftToRight = 0, NSWritingDirectionRightToLeft = 1 } NSWritingDirection;Constants
-
NaturalNSWritingDirectionNaturalUse the Unicode Bidi algorithm rules P2 and P3 to determine which direction to use.
Available in OS X v10.4 and later.
-
LeftToRightNSWritingDirectionLeftToRightUse a left to right writing direction.
Available in OS X v10.2 and later.
-
RightToLeftNSWritingDirectionRightToLeftUse a right to left writing direction.
Available in OS X v10.2 and later.
Import Statement
Objective-C
@import AppKit;Swift
import AppKitAvailability
Available in OS X v10.2 and later.
-
-
These constants define the names of exceptions raised if
NSStringcannot represent a string in a given encoding, or parse a string as a property list.Declaration
Objective-C
extern NSString *NSParseErrorException; extern NSString *NSCharacterConversionException;Constants
-
NSCharacterConversionExceptionNSCharacterConversionExceptionNSStringraises anNSCharacterConversionExceptionif a string cannot be represented in a file-system or string encoding.Available in OS X v10.0 and later.
-
NSParseErrorExceptionNSParseErrorExceptionNSStringraises anNSParseErrorExceptionif a string cannot be parsed as a property list.Available in OS X v10.0 and later.
-
-
The following constants are provided by
NSStringfor use when detecting string encoding from a data object.Declaration
Swift
let NSStringEncodingDetectionSuggestedEncodingsKey: String let NSStringEncodingDetectionDisallowedEncodingsKey: String let NSStringEncodingDetectionUseOnlySuggestedEncodingsKey: String let NSStringEncodingDetectionAllowLossyKey: String let NSStringEncodingDetectionFromWindowsKey: String let NSStringEncodingDetectionLossySubstitutionKey: String let NSStringEncodingDetectionLikelyLanguageKey: StringObjective-C
NSString * const NSStringEncodingDetectionSuggestedEncodingsKey; NSString * const NSStringEncodingDetectionDisallowedEncodingsKey; NSString * const NSStringEncodingDetectionUseOnlySuggestedEncodingsKey; NSString * const NSStringEncodingDetectionAllowLossyKey; NSString * const NSStringEncodingDetectionFromWindowsKey; NSString * const NSStringEncodingDetectionLossySubstitutionKey; NSString * const NSStringEncodingDetectionLikelyLanguageKey;Constants
-
NSStringEncodingDetectionSuggestedEncodingsKeyNSStringEncodingDetectionSuggestedEncodingsKeyOption specifying any suggested string encodings. Use this when you have prior knowledge about the likely or expected encoding. The corresponding value for this key is an
NSArrayofNSNumberobjects that containNSStringEncodingvalues. If this option is unspecified, all allowed encodings are evaluated with equal consideration.Available in OS X v10.10 and later.
-
NSStringEncodingDetectionDisallowedEncodingsKeyNSStringEncodingDetectionDisallowedEncodingsKeyOption specifying any string encodings not to be considered. The corresponding value for this key is an
NSArrayofNSNumberobjects that containNSStringEncodingvalues. If this option is unspecified, no additional string encodings are removed from consideration.Available in OS X v10.10 and later.
-
NSStringEncodingDetectionUseOnlySuggestedEncodingsKeyNSStringEncodingDetectionUseOnlySuggestedEncodingsKeyOption specifying whether to only consider suggested string encodings. Use this only if you specify a value for
NSStringEncodingDetectionSuggestedEncodingsKey. The corresponding value for this key is anNSNumberobject containing a Boolean value. By default, this value is@(NO).Available in OS X v10.10 and later.
-
NSStringEncodingDetectionAllowLossyKeyNSStringEncodingDetectionAllowLossyKeyOption specifying whether to allow lossy string conversion. The corresponding value for this key is an
NSNumberobject containing a Boolean value. If@(NO), the a lossy string encoding may not be chosen. By default, this value is@(YES).Available in OS X v10.10 and later.
-
NSStringEncodingDetectionFromWindowsKeyNSStringEncodingDetectionFromWindowsKeyOption specifying whether to consider string encodings corresponding to Windows codepage numbers. The corresponding value for this key is an
NSNumberobject containing a Boolean value. If@(YES), Windows string encodings are removed from consideration. By default, this value is@(NO).Available in OS X v10.10 and later.
-
NSStringEncodingDetectionLossySubstitutionKeyNSStringEncodingDetectionLossySubstitutionKeyOption specifying the string used to substitute for any unsupported characters when converting to a lossy string encoding. If a
@(NO)value is specified forNSStringEncodingDetectionAllowLossyKey, this option has no effect. The corresponding value for this key is anNSStringobject. By default, this value is U+FFFD.Available in OS X v10.10 and later.
-
NSStringEncodingDetectionLikelyLanguageKeyNSStringEncodingDetectionLikelyLanguageKeyOption specifying the likely two-letter ISO 639-1 language code for the converted string. Use this when you have prior knowledge about the expected language of the converted string. The corresponding value for this key is an
NSStringobject. If no value is specified, the language of the converted string is not considered.Available in OS X v10.10 and later.
Discussion
These constants are used as keys in the options passed to the
stringEncodingForData:encodingOptions:convertedString:usedLossyConversion:method. -
-
A constant to define the maximum number of characters in an
NSStringobject.This constant is not available in OS X v10.5 and later.
Declaration
Objective-C
#define NSMaximumStringLength (INT_MAX-1)Constants
-
NSMaximumStringLengthMaximum number of characters in an
NSStringobject.Available in OS X v10.7 and later.
Availability
Available in OS X v10.0.
Removed in OS X v10.5.
-
Copyright © 2016 Apple Inc. All rights reserved. Terms of Use | Privacy Policy | Updated: 2016-03-21
