iOS Developer Library

Developer

Foundation Framework Reference NSString Class Reference

Options
Deployment Target:

On This Page
Language:

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)string

    Return Value

    An empty string.

    Availability

    Available in iOS 2.0 and later.

    See Also

    – init

  • init() - init Designated Initializer

    Returns an initialized NSString object that contains no characters.

    Declaration

    Swift

    init()

    Objective-C

    - (instancetype)init

    Return Value

    An initialized NSString object that contains no characters. The returned object may be different from the original receiver.

    Availability

    Available in iOS 2.0 and later.

    See Also

    + string

  • Returns an initialized NSString object containing a given number of bytes from a given buffer of bytes interpreted in a given encoding.

    Declaration

    Swift

    convenience init?(bytes bytes: UnsafePointer<Void>, length len: Int, encoding encoding: UInt)

    Objective-C

    - (instancetype)initWithBytes:(const void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding

    Parameters

    bytes

    A buffer of bytes interpreted in the encoding specified by encoding.

    length

    The number of bytes to use from bytes.

    encoding

    The character encoding applied to bytes.

    Return Value

    An initialized NSString object containing length bytes from bytes interpreted using the encoding encoding. 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 nil value is returned.

    Availability

    Available in iOS 2.0 and later.

  • Returns an initialized NSString object 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?(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length len: Int, encoding encoding: UInt, freeWhenDone freeBuffer: Bool)

    Objective-C

    - (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)flag

    Parameters

    bytes

    A buffer of bytes interpreted in the encoding specified by encoding.

    length

    The number of bytes to use from bytes.

    encoding

    The character encoding of bytes.

    flag

    If YEStrue, the receiver releases the memory with free() when it no longer needs the data; if NOfalse it won’t.

    Return Value

    An initialized NSString object containing length bytes from bytes interpreted using the encoding encoding. The returned object may be different from the original receiver.

    Special Considerations

    If an error occurs during the creation of the string, then bytes is not freed even if flag is YEStrue. 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 iOS 2.0 and later.

  • Returns an initialized NSString object that contains a given number of characters from a given C array of UTF–16 code units.

    Declaration

    Swift

    convenience init(characters characters: UnsafePointer<unichar>, length length: Int)

    Objective-C

    - (instancetype)initWithCharacters:(const unichar *)characters length:(NSUInteger)length

    Parameters

    characters

    A C array of UTF–16 code units; the value must not be NULL.

    length

    The number of characters to use from characters.

    Return Value

    An initialized NSString object containing length characters taken from characters. The returned object may be different from the original receiver.

    Availability

    Available in iOS 2.0 and later.

  • Returns an initialized NSString object that contains a given number of characters from a given C array of UTF–16 code units.

    Declaration

    Swift

    convenience init(charactersNoCopy characters: UnsafeMutablePointer<unichar>, length length: Int, freeWhenDone freeBuffer: Bool)

    Objective-C

    - (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)flag

    Parameters

    characters

    A C array of UTF–16 code units.

    length

    The number of characters to use from characters.

    flag

    If YEStrue, the receiver releases the memory with free() when it no longer needs the data; if NOfalse it won’t.

    Return Value

    An initialized NSString object that contains length characters from characters. The returned object may be different from the original receiver.

    Special Considerations

    If an error occurs during the creation of the string, then bytes is not freed even if flag is YEStrue. 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 iOS 2.0 and later.

  • Returns an NSString object initialized by copying the characters from another given string.

    Declaration

    Swift

    convenience init(string aString: String)

    Objective-C

    - (instancetype)initWithString:(NSString *)aString

    Parameters

    aString

    The string from which to copy characters. This value must not be nil.

    Return Value

    An NSString object initialized by copying the characters from aString. The returned object may be different from the original receiver.

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSString object initialized using the characters in a given C array, interpreted according to a given encoding.

    Declaration

    Swift

    convenience init?(CString nullTerminatedCString: UnsafePointer<Int8>, encoding encoding: UInt)

    Objective-C

    - (instancetype)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding

    Parameters

    nullTerminatedCString

    A C array of characters. The array must end with a NULL character; intermediate NULL characters are not allowed.

    encoding

    The encoding of nullTerminatedCString.

    Return Value

    An NSString object initialized using the characters from nullTerminatedCString. The returned object may be different from the original receiver

    Discussion

    If nullTerminatedCString is not a NULL-terminated C string, or encoding does 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 NULL byte in a single unit, which would result in the premature termination of the C string.

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSString object initialized by copying the characters from a given C array of UTF8-encoded bytes.

    Declaration

    Swift

    convenience init?(UTF8String nullTerminatedCString: UnsafePointer<Int8>)

    Objective-C

    - (instancetype)initWithUTF8String:(const char *)bytes

    Parameters

    bytes

    A NULL-terminated C array of bytes in UTF-8 encoding. This value must not be NULL.

    Return Value

    An NSString object initialized by copying the bytes from bytes. The returned object may be different from the original receiver.

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSString object 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

    format

    A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil.

    ...

    A comma-separated list of arguments to substitute into format.

    Return Value

    An NSString object initialized by using format as 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 method localizedStringWithFormat:, or useinitWithFormat:locale: or initWithFormat:locale:arguments:, passing [NSLocale currentLocale] as the locale.

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSString object 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(format format: String, arguments argList: CVaListPointer)

    Objective-C

    - (instancetype)initWithFormat:(NSString *)format arguments:(va_list)argList

    Parameters

    format

    A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil.

    argList

    A list of arguments to substitute into format.

    Return Value

    An NSString object initialized by using format as a template into which the values in argList are 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 iOS 2.0 and later.

  • Returns an NSString object 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 *)format locale:(id)locale, ...

    Parameters

    format

    A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil.

    locale

    An NSLocale object specifying the locale to use. To use the current locale, pass [NSLocale currentLocale]. To use the system locale, pass nil.

    For legacy support, this may be an instance of NSDictionary containing locale information.

    ...

    A comma-separated list of arguments to substitute into format.

    Discussion

    Invokes initWithFormat:locale:arguments: with locale as the locale.

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSString object 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(format format: String, locale locale: AnyObject?, arguments argList: CVaListPointer)

    Objective-C

    - (instancetype)initWithFormat:(NSString *)format locale:(id)locale arguments:(va_list)argList

    Parameters

    format

    A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil.

    locale

    An NSLocale object specifying the locale to use. To use the current locale (specified by user preferences), pass [NSLocale currentLocale]. To use the system locale, pass nil.

    For legacy support, this may be an instance of NSDictionary containing locale information.

    argList

    A list of arguments to substitute into format.

    Return Value

    An NSString object initialized by using format as a template into which values in argList are substituted according the locale information in locale. 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:

    1. va_list myArgs;
    2. NSString *myString = [[NSString alloc] initWithFormat:@"%@: %d\n"
    3. locale:[NSLocale currentLocale]
    4. arguments:myArgs];

    The resulting string has the value “Cost: 32\n”.

    See String Programming Guide for more information.

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSString object initialized by converting given data into UTF–16 code units using a given encoding.

    Declaration

    Swift

    convenience init?(data data: NSData, encoding encoding: UInt)

    Objective-C

    - (instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding

    Parameters

    data

    An NSData object containing bytes in encoding and the default plain text format (that is, pure content with no attributes or other markups) for that encoding.

    encoding

    The encoding used by data.

    Return Value

    An NSString object initialized by converting the bytes in data into UTF–16 code units using encoding. The returned object may be different from the original receiver. Returns nil if the initialization fails for some reason (for example if data does not represent valid data for encoding).

    Availability

    Available in iOS 2.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

    format

    A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil.

    ...

    A comma-separated list of arguments to substitute into format.

    Return Value

    A string created by using format as 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 iOS 2.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

    format

    A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil.

    Raises an NSInvalidArgumentException if format is nil.

    ...

    A comma-separated list of arguments to substitute into format.

    Return Value

    A string created by using format as 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 %f and %d substitutions, and calls descriptionWithLocale: instead of description where necessary.

    This code excerpt creates a string from another string and a float:

    1. NSString *myString = [NSString localizedStringWithFormat:@"%@: %f\n", @"Cost", 1234.56];

    The resulting string has the value “Cost: 1234.560000\n” if the locale is en_US, and “Cost: 1234,560000\n” if the locale is fr_FR.

    See Formatting String Objects for more information.

    Availability

    Available in iOS 2.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 *)chars length:(NSUInteger)length

    Parameters

    chars

    A C array of UTF–16 code units; the value must not be NULL.

    length

    The number of characters to use from chars.

    Return Value

    A string containing length UTF–16 code units taken (starting with the first) from chars.

    Availability

    Available in iOS 2.0 and later.

  • Returns a string created by copying the characters from another given string.

    Declaration

    Objective-C

    + (instancetype)stringWithString:(NSString *)aString

    Parameters

    aString

    The string from which to copy characters. This value must not be nil.

    Return Value

    A string created by copying the characters from aString.

    Availability

    Available in iOS 2.0 and later.

  • Returns a string containing the bytes in a given C array, interpreted according to a given encoding.

    Declaration

    Objective-C

    + (instancetype)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc

    Parameters

    cString

    A C array of bytes. The array must end with a NULL byte; intermediate NULL bytes are not allowed.

    enc

    The encoding of cString.

    Return Value

    A string containing the characters described in cString.

    Discussion

    If cString is not a NULL-terminated C string, or encoding does 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 NULL byte in a single unit, which would result in the premature termination of the C string.

    Availability

    Available in iOS 2.0 and later.

  • Returns a string created by copying the data from a given C array of UTF8-encoded bytes.

    Declaration

    Objective-C

    + (instancetype)stringWithUTF8String:(const char *)bytes

    Parameters

    bytes

    A NULL-terminated C array of bytes in UTF8 encoding.

    Return Value

    A string created by copying the data from bytes.

    Availability

    Available in iOS 2.0 and later.

  • 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 *)path encoding:(NSStringEncoding)enc error:(NSError * _Nullable *)error

    Parameters

    path

    A path to a file.

    enc

    The encoding of the file at path.

    error

    If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, pass in NULL.

    Return Value

    A string created by reading data from the file named by path using the encoding, enc. If the file can’t be opened or there is an encoding error, returns nil.

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSString object initialized by reading data from the file at a given path using a given encoding.

    Declaration

    Swift

    convenience init(contentsOfFile path: String, encoding enc: UInt) throws

    Objective-C

    - (instancetype)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError * _Nullable *)error

    Parameters

    path

    A path to a file.

    enc

    The encoding of the file at path.

    error

    If an error occurs, upon return contains an NSError object that describes the problem. If you are not interested in possible errors, pass in NULL.

    Return Value

    An NSString object initialized by reading data from the file named by path using 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, returns nil.

    Discussion

    Availability

    Available in iOS 2.0 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 *)path usedEncoding:(NSStringEncoding *)enc error:(NSError * _Nullable *)error

    Parameters

    path

    A path to a file.

    enc

    Upon return, if the file is read successfully, contains the encoding used to interpret the file at path.

    error

    If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.

    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, returns nil.

    Discussion

    This method attempts to determine the encoding of the file at path.

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSString object 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(contentsOfFile path: String, usedEncoding enc: UnsafeMutablePointer<UInt>) throws

    Objective-C

    - (instancetype)initWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError * _Nullable *)error

    Parameters

    path

    A path to a file.

    enc

    Upon return, if the file is read successfully, contains the encoding used to interpret the file at path.

    error

    If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, pass in NULL.

    Return Value

    An NSString object initialized by reading data from the file named by path. The returned object may be different from the original receiver. If the file can’t be opened or there is an encoding error, returns nil.

    Discussion

    Availability

    Available in iOS 2.0 and later.

  • Returns a string created by reading data from a given URL interpreted using a given encoding.

    Declaration

    Objective-C

    + (instancetype)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError * _Nullable *)error

    Parameters

    url

    The URL to read.

    enc

    The encoding of the data at url.

    error

    If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.

    Return Value

    A string created by reading data from URL using the encoding, enc. If the URL can’t be opened or there is an encoding error, returns nil.

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSString object initialized by reading data from a given URL interpreted using a given encoding.

    Declaration

    Swift

    convenience init(contentsOfURL url: NSURL, encoding enc: UInt) throws

    Objective-C

    - (instancetype)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError * _Nullable *)error

    Parameters

    url

    The URL to read.

    enc

    The encoding of the file at path.

    error

    If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, pass in NULL.

    Return Value

    An NSString object initialized by reading data from url. The returned object may be different from the original receiver. If the URL can’t be opened or there is an encoding error, returns nil.

    Discussion

    Availability

    Available in iOS 2.0 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 *)url usedEncoding:(NSStringEncoding *)enc error:(NSError * _Nullable *)error

    Parameters

    url

    The URL from which to read data.

    enc

    Upon return, if url is read successfully, contains the encoding used to interpret the data.

    error

    If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.

    Return Value

    A string created by reading data from url. If the URL can’t be opened or there is an encoding error, returns nil.

    Discussion

    This method attempts to determine the encoding at url.

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSString object initialized by reading data from a given URL and returns by reference the encoding used to interpret the data.

    Declaration

    Swift

    convenience init(contentsOfURL url: NSURL, usedEncoding enc: UnsafeMutablePointer<UInt>) throws

    Objective-C

    - (instancetype)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError * _Nullable *)error

    Parameters

    url

    The URL from which to read data.

    enc

    Upon return, if url is read successfully, contains the encoding used to interpret the data.

    error

    If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, pass in NULL.

    Return Value

    An NSString object initialized by reading data from url. If url can’t be opened or the encoding cannot be determined, returns nil. The returned initialized object might be different from the original receiver

    Discussion

    To read data with an unknown encoding, pass 0 as the enc parameter as in:

    1. NSURL *textFileURL = ;
    2. NSStringEncoding encoding = 0;
    3. NSError *error = nil;
    4. NSString *string = [[NSString alloc] initWithContentsOfURL:textFileURL usedEncoding:&encoding error:&error];

    Availability

    Available in iOS 2.0 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, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws

    Objective-C

    - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError * _Nullable *)error

    Parameters

    path

    The file to which to write the receiver. If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.

    useAuxiliaryFile

    If YEStrue, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path. If NOfalse, the receiver is written directly to path. The YEStrue option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.

    enc

    The encoding to use for the output.

    error

    If there is an error, upon return contains an NSError object that describes the problem. If you are not interested in details of errors, you may pass in NULL.

    Return Value

    YEStrue if the file is written successfully, otherwise NOfalse (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 the CFStringEncoding value for the encoding, separated by a semicolon. The CFStringEncoding value 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;0

    • UTF-8;134217984

    • UTF-8;

    • ;3071

    The methods initWithContentsOfFile:usedEncoding:error:, initWithContentsOfURL:usedEncoding:error:, stringWithContentsOfFile:usedEncoding:error:, and stringWithContentsOfURL:usedEncoding:error: use this information to open the file using the right encoding.

    Availability

    Available in iOS 2.0 and later.

  • Writes the contents of the receiver to the URL specified by url using the specified encoding.

    Declaration

    Swift

    func writeToURL(_ url: NSURL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws

    Objective-C

    - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError * _Nullable *)error

    Parameters

    url

    The URL to which to write the receiver. Only file URLs are supported.

    useAuxiliaryFile

    If YEStrue, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to url. If NOfalse, the receiver is written directly to url. The YEStrue option guarantees that url, if it exists at all, won’t be corrupted even if the system should crash during writing.

    The useAuxiliaryFile parameter is ignored if url is not of a type that can be accessed atomically.

    enc

    The encoding to use for the output.

    error

    If there is an error, upon return contains an NSError object that describes the problem. If you are not interested in details of errors, you may pass in NULL.

    Return Value

    YEStrue if the URL is written successfully, otherwise NOfalse (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 the CFStringEncoding value for the encoding, separated by a semicolon. The CFStringEncoding value 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;0

    • UTF-8;134217984

    • UTF-8;

    • ;3071

    The methods initWithContentsOfFile:usedEncoding:error:, initWithContentsOfURL:usedEncoding:error:, stringWithContentsOfFile:usedEncoding:error:, and stringWithContentsOfURL:usedEncoding:error: use this information to open the file using the right encoding.

    Availability

    Available in iOS 2.0 and later.

  • The number of UTF–16 code units in the receiver. (read-only)

    Declaration

    Swift

    var length: Int { get }

    Objective-C

    @property(readonly) NSUInteger length

    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 iOS 2.0 and later.

  • Returns the number of bytes required to store the receiver in a given encoding.

    Declaration

    Swift

    func lengthOfBytesUsingEncoding(_ enc: UInt) -> Int

    Objective-C

    - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc

    Parameters

    enc

    The encoding for which to determine the receiver's length.

    Return Value

    The number of bytes required to store the receiver in the encoding enc in a non-external representation. The length does not include space for a terminating NULL character. Returns 0 if 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 exceed NSIntegerMax.

    Discussion

    The result is exact and is returned in O(n) time.

    Availability

    Available in iOS 2.0 and later.

  • Returns the maximum number of bytes needed to store the receiver in a given encoding.

    Declaration

    Swift

    func maximumLengthOfBytesUsingEncoding(_ enc: UInt) -> Int

    Objective-C

    - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc

    Parameters

    enc

    The encoding for which to determine the receiver's length.

    Return Value

    The maximum number of bytes needed to store the receiver in encoding in a non-external representation. The length does not include space for a terminating NULL character. Returns 0 if the amount of memory required for storing the results of the encoding conversion would exceed NSIntegerMax.

    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 iOS 2.0 and later.

  • Returns the character at a given array position.

    Declaration

    Swift

    func characterAtIndex(_ index: Int) -> unichar

    Objective-C

    - (unichar)characterAtIndex:(NSUInteger)index

    Parameters

    index

    The 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 NSRangeException if index lies beyond the end of the receiver.

    Availability

    Available in iOS 2.0 and later.

  • Copies characters from a given range in the receiver into a given buffer.

    Declaration

    Swift

    func getCharacters(_ buffer: UnsafeMutablePointer<unichar>, range range: NSRange)

    Objective-C

    - (void)getCharacters:(unichar *)buffer range:(NSRange)aRange

    Parameters

    buffer

    Upon return, contains the characters from the receiver. buffer must be large enough to contain the characters in the range aRange (aRange.length*sizeof(unichar)).

    aRange

    The range of characters to retrieve. The range must not exceed the bounds of the receiver.

    Discussion

    This method does not add a NULL character.

    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 iOS 2.0 and later.

  • Gets a given range of characters as bytes in a specified encoding.

    Declaration

    Swift

    func getBytes(_ buffer: UnsafeMutablePointer<Void>, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding encoding: UInt, options options: NSStringEncodingConversionOptions, range range: NSRange, remainingRange leftover: NSRangePointer) -> Bool

    Objective-C

    - (BOOL)getBytes:(void *)buffer maxLength:(NSUInteger)maxBufferCount usedLength:(NSUInteger *)usedBufferCount encoding:(NSStringEncoding)encoding options:(NSStringEncodingConversionOptions)options range:(NSRange)range remainingRange:(NSRangePointer)leftover

    Parameters

    buffer

    A buffer into which to store the bytes from the receiver. The returned bytes are not NULL-terminated.

    maxBufferCount

    The maximum number of bytes to write to buffer.

    usedBufferCount

    The number of bytes used from buffer. Pass NULL if you do not need this value.

    encoding

    The encoding to use for the returned bytes.

    options

    A mask to specify options to use for converting the receiver’s contents to encoding (if conversion is necessary).

    range

    The range of characters in the receiver to get.

    leftover

    The remaining range. Pass NULL If you do not need this value.

    Return Value

    YEStrue if some characters were converted, otherwise NOfalse.

    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 iOS 2.0 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)encoding

    Parameters

    encoding

    The encoding for the returned C string.

    Return Value

    A C string representation of the receiver using the encoding specified by encoding. Returns NULL if the receiver cannot be losslessly converted to encoding.

    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 to encoding. If it can’t, you can use dataUsingEncoding:allowLossyConversion: to get a C-string representation using encoding, allowing some loss of information (note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator).

    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 iOS 2.0 and later.

  • Converts the receiver’s content to a given encoding and stores them in a buffer.

    Declaration

    Swift

    func getCString(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferCount: Int, encoding encoding: UInt) -> Bool

    Objective-C

    - (BOOL)getCString:(char *)buffer maxLength:(NSUInteger)maxBufferCount encoding:(NSStringEncoding)encoding

    Parameters

    buffer

    Upon return, contains the converted C-string plus the NULL termination byte. The buffer must include room for maxBufferCount bytes.

    maxBufferCount

    The maximum number of bytes in the string to return in buffer (including the NULL termination byte).

    encoding

    The encoding for the returned C string.

    Return Value

    YEStrue if the operation was successful, otherwise NOfalse. Returns NOfalse if conversion is not possible due to encoding errors or if buffer is too small.

    Discussion

    Note that in the treatment of the maxBufferCount argument, this method differs from the deprecated getCString:maxLength: method which it replaces. (The buffer should include room for maxBufferCount bytes; this number should accommodate the expected size of the return value plus the NULL termination byte, which this method adds.)

    You can use canBeConvertedToEncoding: to check whether a string can be losslessly converted to encoding. If it can’t, you can use dataUsingEncoding:allowLossyConversion: to get a C-string representation using encoding, allowing some loss of information (note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator).

    Availability

    Available in iOS 2.0 and later.

  • A null-terminated UTF8 representation of the string. (read-only)

    Declaration

    Swift

    var UTF8String: UnsafePointer<Int8> { get }

    Objective-C

    @property(readonly) const char *UTF8String

    Discussion

    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 iOS 2.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

    format

    A 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 format and the following arguments, in the manner of stringWithFormat:.

    Availability

    Available in iOS 2.0 and later.

  • Returns a new string made by appending a given string to the receiver.

    Declaration

    Swift

    func stringByAppendingString(_ aString: String) -> String

    Objective-C

    - (NSString *)stringByAppendingString:(NSString *)aString

    Parameters

    aString

    The string to append to the receiver. This value must not be nil.

    Return Value

    A new string made by appending aString to the receiver.

    Discussion

    This code excerpt, for example:

    1. NSString *errorTag = @"Error: ";
    2. NSString *errorString = @"premature end of file.";
    3. NSString *errorMessage = [errorTag stringByAppendingString:errorString];

    produces the string “Error: premature end of file.”.

    Availability

    Available in iOS 2.0 and later.

  • 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, withString padString: String, startingAtIndex padIndex: Int) -> String

    Objective-C

    - (NSString *)stringByPaddingToLength:(NSUInteger)newLength withString:(NSString *)padString startingAtIndex:(NSUInteger)padIndex

    Parameters

    newLength

    The new length for the receiver.

    padString

    The string with which to extend the receiver.

    padIndex

    The index in padString from 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 padString as necessary.

    Discussion

    Here are some examples of usage:

    1. [@"abc" stringByPaddingToLength: 9 withString: @"." startingAtIndex:0];
    2. // Results in "abc......"
    3. [@"abc" stringByPaddingToLength: 2 withString: @"." startingAtIndex:0];
    4. // Results in "ab"
    5. [@"abc" stringByPaddingToLength: 9 withString: @". " startingAtIndex:1];
    6. // Results in "abc . . ."
    7. // Notice that the first character in the padding is " "

    Availability

    Available in iOS 2.0 and later.

  • Returns an array containing substrings from the receiver that have been divided by a given separator.

    Declaration

    Swift

    func componentsSeparatedByString(_ separator: String) -> [String]

    Objective-C

    - (NSArray<NSString *> *)componentsSeparatedByString:(NSString *)separator

    Parameters

    separator

    The separator string.

    Return Value

    An NSArray object containing substrings from the receiver that have been divided by separator.

    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:

    1. NSString *list = @"Karin, Carrie, David";
    2. NSArray *listItems = [list componentsSeparatedByString:@", "];

    produces an array { @"Karin", @"Carrie", @"David"" }.

    If list begins with a comma and space—for example, @", Norman, Stanley, Fletcher"—the array has these contents: { @"", @"Norman", @"Stanley", @"Fletcher" }

    If list has no separators—for example, "Karin"—the array contains the string itself, in this case { @"Karin" }.

    Availability

    Available in iOS 2.0 and later.

  • 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 *)separator

    Parameters

    separator

    A character set containing the characters to to use to split the receiver. Must not be nil.

    Return Value

    An NSArray object containing substrings from the receiver that have been divided by characters in separator.

    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 iOS 2.0 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) -> String

    Objective-C

    - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set

    Parameters

    set

    A character set containing the characters to remove from the receiver. set must not be nil.

    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 from set, the empty string is returned.

    Discussion

    Use whitespaceCharacterSet or whitespaceAndNewlineCharacterSet to remove whitespace around strings.

    Availability

    Available in iOS 2.0 and later.

  • Returns a new string containing the characters of the receiver from the one at a given index to the end.

    Declaration

    Swift

    func substringFromIndex(_ from: Int) -> String

    Objective-C

    - (NSString *)substringFromIndex:(NSUInteger)anIndex

    Parameters

    anIndex

    An index. The value must lie within the bounds of the receiver, or be equal to the length of the receiver.

    Raises an NSRangeException if (anIndex - 1) lies beyond the end of the receiver.

    Return Value

    A new string containing the characters of the receiver from the one at anIndex to the end. If anIndex is equal to the length of the string, returns an empty string.

    Availability

    Available in iOS 2.0 and later.

  • Returns a string object containing the characters of the receiver that lie within a given range.

    Declaration

    Swift

    func substringWithRange(_ range: NSRange) -> String

    Objective-C

    - (NSString *)substringWithRange:(NSRange)aRange

    Parameters

    aRange

    A range. The range must not exceed the bounds of the receiver.

    Raises an NSRangeException if (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 iOS 2.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

    Swift

    func substringToIndex(_ to: Int) -> String

    Objective-C

    - (NSString *)substringToIndex:(NSUInteger)anIndex

    Parameters

    anIndex

    An index. The value must lie within the bounds of the receiver, or be equal to the length of the receiver.

    Raises an NSRangeException if (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. If anIndex is equal to the length of the string, returns a copy of the receiver.

    Availability

    Available in iOS 2.0 and later.

  • Returns whether the receiver contains a given string by performing a case-sensitive, locale-unaware search.

    Declaration

    Swift

    func containsString(_ str: String) -> Bool

    Objective-C

    - (BOOL)containsString:(NSString *)str

    Parameters

    str

    The string to search for. This value must not be nil.

    Return Value

    YEStrue if the receiver contains str, otherwise NOfalse.

    Discussion

    Calling this method is equivalent to calling rangeOfString:options: with no options.

    Availability

    Available in iOS 8.0 and later.

  • Returns whether the receiver contains a given string by performing a case-insensitive, locale-aware search.

    Declaration

    Swift

    func localizedCaseInsensitiveContainsString(_ str: String) -> Bool

    Objective-C

    - (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str

    Parameters

    str

    The string to search for. This value must not be nil.

    Return Value

    YEStrue if the receiver contains str, otherwise NOfalse.

    Discussion

    Calling this method is equivalent to calling rangeOfString:options: with the NSCaseInsensitiveSearch option.

    Availability

    Available in iOS 8.0 and later.

  • Returns whether the receiver contains a given string by performing a case and diacritic insensitive, locale-aware search.

    Declaration

    Swift

    func localizedStandardContainsString(_ str: String) -> Bool

    Objective-C

    - (BOOL)localizedStandardContainsString:(NSString *)str

    Parameters

    str

    The string to search for. This value must not be nil.

    Return Value

    YEStrue if the receiver contains str, otherwise NOfalse.

    Availability

    Available in iOS 9.0 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

    Swift

    func localizedStandardRangeOfString(_ str: String) -> NSRange

    Objective-C

    - (NSRange)localizedStandardRangeOfString:(NSString *)str

    Parameters

    str

    The string to search for. This value must not be nil.

    Return Value

    The range of the first occurrence of str in the receiver. Returns {NSNotFound, 0} if str is not found.

    Availability

    Available in iOS 9.0 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) -> NSRange

    Objective-C

    - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet

    Parameters

    aSet

    A character set. This value must not be nil.

    Raises an NSInvalidArgumentException if aSet is nil.

    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 in aSet are found.

    Discussion

    Invokes rangeOfCharacterFromSet:options: with no options.

    Availability

    Available in iOS 2.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, options mask: NSStringCompareOptions) -> NSRange

    Objective-C

    - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask

    Parameters

    aSet

    A character set. This value must not be nil.

    Raises an NSInvalidArgumentException if aSet is nil.

    mask

    A mask specifying search options. The following options may be specified by combining them with the C bitwise OR operator: 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 in aSet are found.

    Discussion

    Invokes rangeOfCharacterFromSet:options:range: with mask for the options and the entire extent of the receiver for the range.

    Availability

    Available in iOS 2.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, options mask: NSStringCompareOptions, range searchRange: NSRange) -> NSRange

    Objective-C

    - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask range:(NSRange)aRange

    Parameters

    aSet

    A character set. This value must not be nil.

    Raises an NSInvalidArgumentException if aSet is nil.

    mask

    A mask specifying search options. The following options may be specified by combining them with the C bitwise OR operator: NSAnchoredSearch, NSBackwardsSearch.

    aRange

    The range in which to search. aRange must not exceed the bounds of the receiver.

    Raises an NSRangeException if aRange is invalid.

    Return Value

    The range in the receiver of the first character found from aSet within aRange. Returns a range of {NSNotFound, 0} if none of the characters in aSet are 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 iOS 2.0 and later.

  • Finds and returns the range of the first occurrence of a given string within the receiver.

    Declaration

    Swift

    func rangeOfString(_ searchString: String) -> NSRange

    Objective-C

    - (NSRange)rangeOfString:(NSString *)aString

    Parameters

    aString

    The string to search for. This value must not be nil.

    Raises an NSInvalidArgumentException if aString is nil.

    Return Value

    An NSRange structure giving the location and length in the receiver of the first occurrence of aString. Returns {NSNotFound, 0} if aString is not found or is empty (@"").

    Discussion

    Invokes rangeOfString:options: with no options.

    Availability

    Available in iOS 2.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, options mask: NSStringCompareOptions) -> NSRange

    Objective-C

    - (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask

    Parameters

    aString

    The string to search for. This value must not be nil.

    mask

    A mask specifying search options. The following options may be specified by combining them with the C bitwise OR operator: NSCaseInsensitiveSearch, NSLiteralSearch, NSBackwardsSearch, NSAnchoredSearch. See String Programming Guide for details on these options.

    Return Value

    An NSRange structure giving the location and length in the receiver of the first occurrence of aString, modulo the options in mask. Returns {NSNotFound, 0} if aString is not found or is empty (@"").

    Discussion

    Invokes rangeOfString:options:range: with the options specified by mask and the entire extent of the receiver as the range.

    Availability

    Available in iOS 2.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, options mask: NSStringCompareOptions, range searchRange: NSRange) -> NSRange

    Objective-C

    - (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange

    Parameters

    aString

    The string for which to search. This value must not be nil.

    Raises an NSInvalidArgumentException if aString is nil.

    mask

    A mask specifying search options. The following options may be specified by combining them with the C bitwise OR operator: NSCaseInsensitiveSearch, NSLiteralSearch, NSBackwardsSearch, NSAnchoredSearch. See String Programming Guide for details on these options.

    aRange

    The range within the receiver for which to search for aString.

    Raises an NSRangeException if aRange is invalid.

    Return Value

    An NSRange structure giving the location and length in the receiver of aString within aRange in the receiver, modulo the options in mask. The range returned is relative to the start of the string, not to the passed-in range. Returns {NSNotFound, 0} if aString is not found or is empty (@"").

    Discussion

    The length of the returned range and that of aString may 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 iOS 2.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, options mask: NSStringCompareOptions, range searchRange: NSRange, locale locale: NSLocale?) -> NSRange

    Objective-C

    - (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange locale:(NSLocale *)locale

    Parameters

    aString

    The string for which to search. This value must not be nil.

    Raises an NSInvalidArgumentException if aString is nil.

    mask

    A mask specifying search options. The following options may be specified by combining them with the C bitwise OR operator: NSCaseInsensitiveSearch, NSLiteralSearch, NSBackwardsSearch, NSAnchoredSearch. See String Programming Guide for details on these options.

    aRange

    The range within the receiver for which to search for aString.

    Raises an NSRangeException if aRange is invalid.

    locale

    The locale to use when comparing the receiver with aString. To use the current locale, pass [NSLocale currentLocale]. To use the system locale, pass nil.

    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 NSRange structure giving the location and length in the receiver of aString within aRange in the receiver, modulo the options in mask. The range returned is relative to the start of the string, not to the passed-in range. Returns {NSNotFound, 0} if aString is not found or is empty (@"").

    Discussion

    The length of the returned range and that of aString may 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 iOS 2.0 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))block

    Parameters

    block

    The block executed for the enumeration.

    The block takes two arguments:

    line

    The 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.

    stop

    A reference to a Boolean value that the block can use to stop the enumeration by setting *stop = YES; it should not touch *stop otherwise.

    Availability

    Available in iOS 4.0 and later.

  • Enumerates the substrings of the specified type in the specified range of the string.

    Declaration

    Swift

    func enumerateSubstringsInRange(_ range: NSRange, options opts: NSStringEnumerationOptions, usingBlock block: (String?, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void)

    Objective-C

    - (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))block

    Parameters

    range

    The range within the string to enumerate substrings.

    opts

    Options specifying types of substrings and enumeration styles.

    block

    The block executed for the enumeration.

    The block takes four arguments:

    substring

    The enumerated string.

    substringRange

    The range of the enumerated string in the receiver.

    enclosingRange

    The range that includes the substring as well as any separator or filler characters that follow. For instance, for lines, enclosingRange contains the line terminators. The enclosingRange for 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.

    stop

    A reference to a Boolean value that the block can use to stop the enumeration by setting *stop = YES; it should not touch *stop otherwise.

    Discussion

    If this method is sent to an instance of NSMutableString, mutation (deletion, addition, or change) is allowed, as long as it is within enclosingRange. 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 iOS 4.0 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>, end lineEndPtr: UnsafeMutablePointer<Int>, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>, forRange range: NSRange)

    Objective-C

    - (void)getLineStart:(NSUInteger *)startIndex end:(NSUInteger *)lineEndIndex contentsEnd:(NSUInteger *)contentsEndIndex forRange:(NSRange)aRange

    Parameters

    startIndex

    Upon return, contains the index of the first character of the line containing the beginning of aRange. Pass NULL if you do not need this value (in which case the work to compute the value isn’t performed).

    lineEndIndex

    Upon return, contains the index of the first character past the terminator of the line containing the end of aRange. Pass NULL if you do not need this value (in which case the work to compute the value isn’t performed).

    contentsEndIndex

    Upon return, contains the index of the first character of the terminator of the line containing the end of aRange. Pass NULL if you do not need this value (in which case the work to compute the value isn’t performed).

    aRange

    A range within the receiver. The value must not exceed the bounds of the receiver.

    Raises an NSRangeException if aRange is invalid.

    Discussion

    A line is delimited by any of these characters, the longest possible sequence being preferred to any shorter:

    • U+000A Unicode Character 'LINE FEED (LF)' (\n)

    • U+000D Unicode Character 'CARRIAGE RETURN (CR)' (\r)

    • U+0085 Unicode Character 'NEXT LINE (NEL)'

    • U+2028 Unicode Character 'LINE SEPARATOR'

    • U+2029 Unicode Character 'PARAGRAPH SEPARATOR'

    • \r\n, in that order (also known as CRLF)

    If aRange is 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 iOS 2.0 and later.

  • Returns the range of characters representing the line or lines containing a given range.

    Declaration

    Swift

    func lineRangeForRange(_ range: NSRange) -> NSRange

    Objective-C

    - (NSRange)lineRangeForRange:(NSRange)aRange

    Parameters

    aRange

    A 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. See getLineStart:end:contentsEnd:forRange: for a discussion of line terminators.

    Availability

    Available in iOS 2.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>, end parEndPtr: UnsafeMutablePointer<Int>, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>, forRange range: NSRange)

    Objective-C

    - (void)getParagraphStart:(NSUInteger *)startIndex end:(NSUInteger *)endIndex contentsEnd:(NSUInteger *)contentsEndIndex forRange:(NSRange)aRange

    Parameters

    startIndex

    Upon return, contains the index of the first character of the paragraph containing the beginning of aRange. Pass NULL if you do not need this value (in which case the work to compute the value isn’t performed).

    endIndex

    Upon return, contains the index of the first character past the terminator of the paragraph containing the end of aRange. Pass NULL if you do not need this value (in which case the work to compute the value isn’t performed).

    contentsEndIndex

    Upon return, contains the index of the first character of the terminator of the paragraph containing the end of aRange. Pass NULL if you do not need this value (in which case the work to compute the value isn’t performed).

    aRange

    A range within the receiver. The value must not exceed the bounds of the receiver.

    Discussion

    If aRange is contained with a single paragraph, of course, the returned indexes all belong to that paragraph. Similar to getLineStart:end:contentsEnd:forRange:, you can use the results of this method to construct the ranges for paragraphs.

    Availability

    Available in iOS 2.0 and later.

  • Returns the range of characters representing the paragraph or paragraphs containing a given range.

    Declaration

    Swift

    func paragraphRangeForRange(_ range: NSRange) -> NSRange

    Objective-C

    - (NSRange)paragraphRangeForRange:(NSRange)aRange

    Parameters

    aRange

    A 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 iOS 2.0 and later.

  • Returns the range in the receiver of the composed character sequence located at a given index.

    Declaration

    Swift

    func rangeOfComposedCharacterSequenceAtIndex(_ index: Int) -> NSRange

    Objective-C

    - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex

    Parameters

    anIndex

    The 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 iOS 2.0 and later.

  • Returns the range in the string of the composed character sequences for a given range.

    Declaration

    Swift

    func rangeOfComposedCharacterSequencesForRange(_ range: NSRange) -> NSRange

    Objective-C

    - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range

    Parameters

    range

    A 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 iOS 2.0 and later.

  • Parses the receiver as a text representation of a property list, returning an NSString, NSData, NSArray, or NSDictionary object, according to the topmost element.

    Declaration

    Swift

    func propertyList() -> AnyObject

    Objective-C

    - (id)propertyList

    Return Value

    A property list representation of returning an NSString, NSData, NSArray, or NSDictionary object, 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 iOS 2.0 and later.

  • Returns a dictionary object initialized with the keys and values found in the receiver.

    Declaration

    Swift

    func propertyListFromStringsFileFormat() -> [NSObject : AnyObject]?

    Objective-C

    - (NSDictionary *)propertyListFromStringsFileFormat

    Return 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 .strings files. 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:

    1. /* Question in confirmation panel for quitting. */
    2. "Confirm Quit" = "Are you sure you want to quit?";
    3. /* Message when user tries to close unsaved document */
    4. "Close or Save" = "Save changes before closing?";
    5. /* Word for Cancel */
    6. "Cancel";

    Availability

    Available in iOS 2.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

    Swift

    func drawAtPoint(_ point: CGPoint, withAttributes attrs: [String : AnyObject]?)

    Objective-C

    - (void)drawAtPoint:(CGPoint)point withAttributes:(NSDictionary<NSString *,id> *)attrs

    Parameters

    point

    The 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.

    attrs

    A dictionary of text attributes to be applied to the string. These are the same attributes that can be applied to an NSAttributedString object, but in the case of NSString objects, 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 UIKit;

    Swift

    import UIKit

    Availability

    Available in iOS 7.0 and later.

  • Draws the attributed string inside the specified bounding rectangle.

    Declaration

    Swift

    func drawInRect(_ rect: CGRect, withAttributes attrs: [String : AnyObject]?)

    Objective-C

    - (void)drawInRect:(CGRect)rect withAttributes:(NSDictionary<NSString *,id> *)attrs

    Parameters

    rect

    The 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.

    attrs

    The text attributes with which to draw the string. These are the same attributes that can be applied to an NSAttributedString object, but in the case of NSString objects, 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 UIKit;

    Swift

    import UIKit

    Availability

    Available in iOS 7.0 and later.

  • Draws the attributed string in the specified bounding rectangle using the provided options.

    Declaration

    Swift

    func drawWithRect(_ rect: CGRect, options options: NSStringDrawingOptions, attributes attributes: [String : AnyObject]?, context context: NSStringDrawingContext?)

    Objective-C

    - (void)drawWithRect:(CGRect)rect options:(NSStringDrawingOptions)options attributes:(NSDictionary<NSString *,id> *)attributes context:(NSStringDrawingContext *)context

    Parameters

    rect

    The bounding rectangle in which to draw the string.

    options

    Additional drawing options to apply to the string during rendering. For a list of possible values, see NSStringDrawingOptions.

    attributes

    The text attributes with which to draw the string. These are the same attributes that can be applied to an NSAttributedString object, but in the case of NSString objects, the attributes apply to the entire string, rather than ranges within the string.

    context

    A 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 NSStringDrawingUsesLineFragmentOrigin in the options parameter.

    Special Considerations

    This method uses the baseline origin by default.

    If NSStringDrawingUsesLineFragmentOrigin is not specified, the rectangle’s height will be ignored and the operation considered to be single-line rendering.

    Import Statement

    Objective-C

    @import UIKit;

    Swift

    import UIKit

    Availability

    Available in iOS 7.0 and later.

  • 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: CGSize, options options: NSStringDrawingOptions, attributes attributes: [String : AnyObject]?, context context: NSStringDrawingContext?) -> CGRect

    Objective-C

    - (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary<NSString *,id> *)attributes context:(NSStringDrawingContext *)context

    Parameters

    size

    The size of the rectangle to draw in.

    options

    String drawing options.

    attributes

    A dictionary of text attributes to be applied to the string. These are the same attributes that can be applied to an NSAttributedString object, but in the case of NSString objects, the attributes apply to the entire string, rather than ranges within the string.

    context

    The 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 NSStringDrawingUsesLineFragmentOrigin in the options parameter.

    This method returns fractional sizes (in the size component of the returned CGRect); to use a returned size to size views, you must raise its value to the nearest higher integer using the ceil function.

    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 CGRect can exceed the width value of the size parameter.

    Import Statement

    Objective-C

    @import UIKit;

    Swift

    import UIKit

    Availability

    Available in iOS 7.0 and later.

  • Returns the bounding box size the receiver occupies when drawn with the given attributes.

    Declaration

    Swift

    func sizeWithAttributes(_ attrs: [String : AnyObject]?) -> CGSize

    Objective-C

    - (CGSize)sizeWithAttributes:(NSDictionary<NSString *,id> *)attrs

    Parameters

    attrs

    A dictionary of text attributes to be applied to the string. These are the same attributes that can be applied to an NSAttributedString object, but in the case of NSString objects, 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 ceil function.

    Import Statement

    Objective-C

    @import UIKit;

    Swift

    import UIKit

    Availability

    Available in iOS 7.0 and later.

  • Returns a string with the given character folding options applied.

    Declaration

    Swift

    func stringByFoldingWithOptions(_ options: NSStringCompareOptions, locale locale: NSLocale?) -> String

    Objective-C

    - (NSString *)stringByFoldingWithOptions:(NSStringCompareOptions)options locale:(NSLocale *)locale

    Parameters

    options

    A mask of compare flags with a suffix InsensitiveSearch.

    locale

    The locale to use for the folding. To use the current locale, pass [NSLocale currentLocale]. To use the system locale, pass nil.

    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 iOS 2.0 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, options mask: NSStringCompareOptions) -> String

    Objective-C

    - (NSString *)commonPrefixWithString:(NSString *)aString options:(NSStringCompareOptions)mask

    Parameters

    aString

    The string with which to compare the receiver.

    mask

    Options for the comparison. The following search options may be specified by combining them with the C bitwise OR operator: NSCaseInsensitiveSearch, NSLiteralSearch. See String Programming Guide for details on these options.

    Return Value

    A string containing characters the receiver and aString have 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 aString is “Mädchenschule”, the string returned is “Ma¨dchen”, not “Mädchen”.

    Availability

    Available in iOS 2.0 and later.

    See Also

    – hasPrefix:

  • A capitalized representation of the receiver. (read-only)

    Declaration

    Swift

    var capitalizedString: String { get }

    Objective-C

    @property(readonly, copy) NSString *capitalizedString

    Discussion

    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 lowercaseString for an example.

    Availability

    Available in iOS 2.0 and later.

  • Returns a capitalized representation of the receiver using the specified locale.

    Declaration

    Swift

    func capitalizedStringWithLocale(_ locale: NSLocale?) -> String

    Objective-C

    - (NSString *)capitalizedStringWithLocale:(NSLocale *)locale

    Parameters

    locale

    The locale. For strings presented to users, pass the current locale ([NSLocale currentLocale]). To use the system locale, pass nil.

    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 iOS 6.0 and later.

  • A lowercase representation of the string.

    Declaration

    Swift

    var lowercaseString: String { get }

    Objective-C

    @property(readonly, copy) NSString *lowercaseString

    Discussion

    Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. The result of this statement:

    1. lcString = [myString lowercaseString];

    might not be equal to this statement:

    1. 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 iOS 2.0 and later.

  • Returns a version of the string with all letters converted to lowercase, taking into account the specified locale.

    Declaration

    Swift

    func lowercaseStringWithLocale(_ locale: NSLocale?) -> String

    Objective-C

    - (NSString *)lowercaseStringWithLocale:(NSLocale *)locale

    Parameters

    locale

    The locale. For strings presented to users, pass the current locale ([NSLocale currentLocale]). To use the system local, pass nil.

    Return Value

    A lowercase string using the locale. Input of @"ABcde" would result in a return of @"abcde".

    Discussion

    .

    Availability

    Available in iOS 6.0 and later.

  • An uppercase representation of the string. (read-only)

    Declaration

    Swift

    var uppercaseString: String { get }

    Objective-C

    @property(readonly, copy) NSString *uppercaseString

    Discussion

    Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See lowercaseString for an example.

    Availability

    Available in iOS 2.0 and later.

  • Returns a version of the string with all letters converted to uppercase, taking into account the specified locale.

    Declaration

    Swift

    func uppercaseStringWithLocale(_ locale: NSLocale?) -> String

    Objective-C

    - (NSString *)uppercaseStringWithLocale:(NSLocale *)locale

    Parameters

    locale

    The locale. For strings presented to users, pass the current locale ([NSLocale currentLocale]). To use the system locale, pass nil.

    Return Value

    An uppercase string using the locale. Input of @"ABcde" would result in a return of @"ABCDE".

    Availability

    Available in iOS 6.0 and later.

  • The floating-point value of the string as a double. (read-only)

    Declaration

    Swift

    var doubleValue: Double { get }

    Objective-C

    @property(readonly) double doubleValue

    Discussion

    This property doesn’t include any whitespace at the beginning of the string. This property is HUGE_VAL or -HUGE_VAL on overflow, 0.0 on underflow. This property is 0.0 if 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 NSScanner object for localized scanning of numeric values from a string.

    Availability

    Available in iOS 2.0 and later.

  • The floating-point value of the string as a float. (read-only)

    Declaration

    Swift

    var floatValue: Float { get }

    Objective-C

    @property(readonly) float floatValue

    Discussion

    This property doesn’t include whitespace at the beginning of the string. This property is HUGE_VAL or -HUGE_VAL on overflow, 0.0 on underflow. This property is 0.0 if 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 NSScanner object for localized scanning of numeric values from a string.

    Availability

    Available in iOS 2.0 and later.

  • The integer value of the string. (read-only)

    Declaration

    Swift

    var intValue: Int32 { get }

    Objective-C

    @property(readonly) int intValue

    Discussion

    The integer value of the string, assuming a decimal representation and skipping whitespace at the beginning of the string. This property is INT_MAX or INT_MIN on overflow. This property is 0 if 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 NSScanner object for localized scanning of numeric values from a string.

    Special Considerations

    On OS X v10.5 and later, use integerValue instead.

    Availability

    Available in iOS 2.0 and later.

  • The NSInteger value of the string. (read-only)

    Declaration

    Swift

    var integerValue: Int { get }

    Objective-C

    @property(readonly) NSInteger integerValue

    Discussion

    The NSInteger value of the string, assuming a decimal representation and skipping whitespace at the beginning of the string. This property is 0 if 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 NSScanner object for localized scanning of numeric values from a string.

    Availability

    Available in iOS 2.0 and later.

    See Also

    doubleValue
    floatValue
    scanInt: (NSScanner)

  • The long long value of the string. (read-only)

    Declaration

    Swift

    var longLongValue: Int64 { get }

    Objective-C

    @property(readonly) long long longLongValue

    Discussion

    The long long value of the string, assuming a decimal representation and skipping whitespace at the beginning of the string. This property is LLONG_MAX or LLONG_MIN on overflow. This property is 0 if 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 NSScanner object for localized scanning of numeric values from a string.

    Availability

    Available in iOS 2.0 and later.

    See Also

    doubleValue
    floatValue
    scanInt: (NSScanner)

  • The Boolean value of the string. (read-only)

    Declaration

    Swift

    var boolValue: Bool { get }

    Objective-C

    @property(readonly) BOOL boolValue

    Discussion

    This property is YEStrue on encountering one of "Y", "y", "T", "t", or a digit 1-9—the method ignores any trailing characters. This property is NOfalse if 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 iOS 2.0 and later.

    See Also

    integerValue
    scanInt: (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 *)availableStringEncodings

    Return 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 CFStringConvertEncodingToNSStringEncoding function to convert them to a usable format.

    Availability

    Available in iOS 2.0 and later.

  • Returns the C-string encoding assumed for any method accepting a C string as an argument.

    Declaration

    Swift

    class func defaultCStringEncoding() -> UInt

    Objective-C

    + (NSStringEncoding)defaultCStringEncoding

    Return 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 NSString content—for example, punctuation characters with a bidirectional encoding.

    Methods that accept a C string as an argument use ...CString... in the keywords for such arguments: for example, stringWithCString:—note, though, that these are deprecated. The default C-string encoding is determined from system information and can’t be changed programmatically for an individual process. See NSStringEncoding for a full list of supported encodings.

    Availability

    Available in iOS 2.0 and later.

  • 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, encodingOptions opts: [String : AnyObject]?, convertedString string: AutoreleasingUnsafeMutablePointer<NSString?>, usedLossyConversion usedLossyConversion: UnsafeMutablePointer<ObjCBool>) -> UInt

    Objective-C

    + (NSStringEncoding)stringEncodingForData:(NSData *)data encodingOptions:(NSDictionary<NSString *,id> *)opts convertedString:(NSString * _Nullable *)string usedLossyConversion:(BOOL *)usedLossyConversion

    Parameters

    data

    An NSData object containing bytes in an encoding to be determined.

    opts

    Options to use when attempting to determine the string encoding. See String Encoding Detection Options for a full list of supported options.

    string

    If a string encoding could be determined, upon return contains an NSString object constructed from data using the determined string encoding.

    usedLossyConversion

    If a string encoding could be determined, upon return contains a BOOL value corresponding to whether lossy conversion was used.

    Return Value

    An NSStringEncoding value, or 0 if a string encoding could not be determined.

    Availability

    Available in iOS 8.0 and later.

  • Returns a human-readable string giving the name of a given encoding.

    Declaration

    Swift

    class func localizedNameOfStringEncoding(_ encoding: UInt) -> String

    Objective-C

    + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding

    Parameters

    encoding

    A string encoding.

    Return Value

    A human-readable string giving the name of encoding in the current locale.

    Availability

    Available in iOS 2.0 and later.

  • Returns a Boolean value that indicates whether the receiver can be converted to a given encoding without loss of information.

    Declaration

    Swift

    func canBeConvertedToEncoding(_ encoding: UInt) -> Bool

    Objective-C

    - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding

    Parameters

    encoding

    A string encoding.

    Return Value

    YEStrue if the receiver can be converted to encoding without loss of information. Returns NOfalse if 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 return nil on failure, so you can avoid the overhead of invoking this method yourself by simply trying to convert the string.

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSData object containing a representation of the receiver encoded using a given encoding.

    Declaration

    Swift

    func dataUsingEncoding(_ encoding: UInt) -> NSData?

    Objective-C

    - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding

    Parameters

    encoding

    A string encoding.

    Return Value

    The result of invoking dataUsingEncoding:allowLossyConversion: with NOfalse as the second argument (that is, requiring lossless conversion).

    Availability

    Available in iOS 2.0 and later.

  • Returns an NSData object containing a representation of the receiver encoded using a given encoding.

    Declaration

    Swift

    func dataUsingEncoding(_ encoding: UInt, allowLossyConversion lossy: Bool) -> NSData?

    Objective-C

    - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)flag

    Parameters

    encoding

    A string encoding.

    flag

    If YEStrue, then allows characters to be removed or altered in conversion.

    Return Value

    An NSData object containing a representation of the receiver encoded using encoding. Returns nil if flag is NOfalse and the receiver can’t be converted without losing some information (such as accents or case).

    Discussion

    If flag is YEStrue and the receiver can’t be converted without losing some information, some characters may be removed or altered in conversion. For example, in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding, the character ‘Á’ becomes ‘A’, losing the accent.

    This method creates an external representation (with a byte order marker, if necessary, to indicate endianness) to ensure that the resulting NSData object 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 iOS 2.0 and later.

  • This NSString object. (read-only)

    Declaration

    Swift

    var description: String { get }

    Objective-C

    @property(readonly, copy) NSString *description

    Availability

    Available in iOS 2.0 and later.

  • The 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 fastestEncoding

    Discussion

    “Fastest” applies to retrieval of characters from the string. This encoding may not be space efficient.

    Availability

    Available in iOS 2.0 and later.

  • The 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 smallestEncoding

    Discussion

    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 iOS 2.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

    Swift

    class func pathWithComponents(_ components: [String]) -> String

    Objective-C

    + (NSString *)pathWithComponents:(NSArray<NSString *> *)components

    Parameters

    components

    An array of NSString objects 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 components by 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 stringByStandardizingPath to resolve empty components, references to the parent directory, and so on.

    Availability

    Available in iOS 2.0 and later.

  • The file-system path components of the receiver. (read-only)

    Declaration

    Swift

    var pathComponents: [String] { get }

    Objective-C

    @property(readonly, copy) NSArray <NSString *> *pathComponents

    Discussion

    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:

    1. NSString *path = @"tmp/scratch";
    2. 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 iOS 2.0 and later.

  • 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?>, caseSensitive flag: Bool, matchesIntoArray outputArray: AutoreleasingUnsafeMutablePointer<NSArray?>, filterTypes filterTypes: [String]?) -> Int

    Objective-C

    - (NSUInteger)completePathIntoString:(NSString * _Nonnull *)outputName caseSensitive:(BOOL)flag matchesIntoArray:(NSArray<NSString *> * _Nonnull *)outputArray filterTypes:(NSArray<NSString *> *)filterTypes

    Parameters

    outputName

    Upon return, contains the longest path that matches the receiver.

    flag

    If YEStrue, the method considers case for possible completions.

    outputArray

    Upon return, contains all matching filenames.

    filterTypes

    An array of NSString objects specifying path extensions to consider for completion. Only paths whose extensions (not including the extension separator) match one of these strings are included in outputArray. Pass nil if you don’t want to filter the output.

    Return Value

    0 if no matches are found and 1 if exactly one match is found. In the case of multiple matches, returns the actual number of matching paths if outputArray is provided, or simply a positive value if outputArray is NULL.

    Discussion

    You can check for the existence of matches without retrieving by passing NULL as outputArray.

    Note that this method only works with file paths (not, for example, string representations of URLs).

    Availability

    Available in iOS 2.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 *fileSystemRepresentation

    Discussion

    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 NSCharacterConversionException if 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 an NSString object, use the stringWithFileSystemRepresentation:length: method on NSFileManager.

    Availability

    Available in iOS 2.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>, maxLength max: Int) -> Bool

    Objective-C

    - (BOOL)getFileSystemRepresentation:(char *)buffer maxLength:(NSUInteger)maxLength

    Parameters

    buffer

    Upon return, contains a C-string that represent the receiver as as a system-independent path, plus the NULL termination byte. The size of buffer must be large enough to contain maxLength bytes.

    maxLength

    The maximum number of bytes in the string to return in buffer (including a terminating NULL character, which this method adds).

    Return Value

    YEStrue if buffer is successfully filled with a file-system representation, otherwise NOfalse (for example, if maxLength would 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 maxLength argument. The first method invocation returns failure as the file representation of the string (@"/mach_kernel") is 12 bytes long and the value passed as the maxLength argument (12) does not allow for the addition of a NULL termination byte.

    1. char filenameBuffer[13];
    2. BOOL success;
    3. success = [@"/mach_kernel" getFileSystemRepresentation:filenameBuffer maxLength:12];
    4. // success == NO
    5. // Changing the length to include the NULL character does work
    6. success = [@"/mach_kernel" getFileSystemRepresentation:filenameBuffer maxLength:13];
    7. // success == YES

    Availability

    Available in iOS 2.0 and later.

  • A 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 absolutePath

    Discussion

    YEStrue if the receiver (if interpreted as a path) represents an absolute path, otherwise NOfalse.

    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 in NSFileManager for that task).

    Availability

    Available in iOS 2.0 and later.

  • The last path component of the receiver. (read-only)

    Declaration

    Swift

    var lastPathComponent: String { get }

    Objective-C

    @property(readonly, copy) NSString *lastPathComponent

    Discussion

    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 lastPathComponent on 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 iOS 2.0 and later.

    See Also

    pathComponents

  • The 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 *pathExtension

    Discussion

    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 pathExtension on 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 iOS 2.0 and later.

  • 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 *stringByAbbreviatingWithTildeInPath

    Discussion

    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.txt for 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 iOS 2.0 and later.

  • Returns a new string made by appending to the receiver a given string.

    Declaration

    Swift

    func stringByAppendingPathComponent(_ str: String) -> String

    Objective-C

    - (NSString *)stringByAppendingPathComponent:(NSString *)aString

    Parameters

    aString

    The path component to append to the receiver.

    Return Value

    A new string made by appending aString to 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 aString is 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 iOS 2.0 and later.

  • Returns a new string made by appending to the receiver an extension separator followed by a given extension.

    Declaration

    Swift

    func stringByAppendingPathExtension(_ str: String) -> String?

    Objective-C

    - (NSString *)stringByAppendingPathExtension:(NSString *)ext

    Parameters

    ext

    The 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 ext is 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 iOS 2.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 *stringByDeletingLastPathComponent

    Discussion

    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 iOS 2.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 *stringByDeletingPathExtension

    Discussion

    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 iOS 2.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 *stringByExpandingTildeInPath

    Discussion

    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 iOS 2.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 *stringByResolvingSymlinksInPath

    Discussion

    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 self if an error occurs.

    Note that this method only works with file paths (not, for example, string representations of URLs).

    Availability

    Available in iOS 2.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 *stringByStandardizingPath

    Discussion

    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 self if 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 iOS 2.0 and later.

  • Returns an array of strings made by separately appending to the receiver each string in in a given array.

    Declaration

    Swift

    func stringsByAppendingPaths(_ paths: [String]) -> [String]

    Objective-C

    - (NSArray<NSString *> *)stringsByAppendingPaths:(NSArray<NSString *> *)paths

    Parameters

    paths

    An array of NSString objects specifying paths to add to the receiver.

    Return Value

    An array of NSString objects made by separately appending each string in paths to 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 iOS 2.0 and later.

  • Creates a new string using a given C-string.

    Deprecation Statement

    Use stringWithCString:encoding: instead.

    Declaration

    Objective-C

    + (id)stringWithCString:(const char *)bytes

    Discussion

    cString should contain data in the default C string encoding. If the argument passed to stringWithCString: is not a zero-terminated C-string, the results are undefined.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • Initializes the receiver, a newly allocated NSString object, 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 *)bytes

    Discussion

    cString must be a zero-terminated C string in the default C string encoding, and may not be NULL. 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 iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • Returns a string containing the characters in a given C-string.

    Deprecation Statement

    Use stringWithCString:encoding: instead.

    Declaration

    Objective-C

    + (id)stringWithCString:(const char *)bytes length:(NSUInteger)length

    Discussion

    cString must not be NULL. cString should contain characters in the default C-string encoding. This method converts length * sizeof(char) bytes from cString and doesn’t stop short at a NULL character.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • Initializes the receiver, a newly allocated NSString object, 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 *)bytes length:(NSUInteger)length

    Discussion

    This method converts length * sizeof(char) bytes from cString and doesn’t stop short at a zero character. cString must contain bytes in the default C-string encoding and may not be NULL. Returns an initialized object, which might be different from the original receiver.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • Initializes the receiver, a newly allocated NSString object, 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 *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer

    Discussion

    This method converts length * sizeof(char) bytes from cString and doesn’t stop short at a zero character. cString must contain data in the default C-string encoding and may not be NULL. The receiver becomes the owner of cString; if flag is YEStrue it will free the memory when it no longer needs it, but if flag is NOfalse it 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 the freeWhenDone argument to initWithStringNoCopy is NOfalse, the C string passed as the method’s first argument cannot be modified, so you can safely use initWithStringNoCopy to create an immutable string from an immutable (const char *) C-string buffer.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • Returns a string created by reading data from the file named by a given path.

    Declaration

    Objective-C

    + (id)stringWithContentsOfFile:(NSString *)path

    Discussion

    If the contents begin with a Unicode 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 nil if the file can’t be opened.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • Initializes the receiver, a newly allocated NSString object, by reading data from the file named by path.

    Declaration

    Objective-C

    - (id)initWithContentsOfFile:(NSString *)path

    Discussion

    Initializes the receiver, a newly allocated NSString object, by reading data from the file named by path. If the contents begin with a byte-order mark (U+FEFF or U+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, or nil if the file can’t be opened.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • Returns a string created by reading data from the file named by a given URL.

    Declaration

    Objective-C

    + (id)stringWithContentsOfURL:(NSURL *)url

    Discussion

    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 nil if the location can’t be opened.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • Initializes the receiver, a newly allocated NSString object, by reading data from the location named by a given URL.

    Declaration

    Objective-C

    - (id)initWithContentsOfURL:(NSURL *)url

    Discussion

    Initializes the receiver, a newly allocated NSString object, by reading data from the location named by aURL. If the contents begin with a byte-order mark (U+FEFF or U+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, or nil if the location can’t be opened.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • 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 *)path atomically:(BOOL)useAuxiliaryFile

    Return Value

    YEStrue if the file is written successfully, otherwise NOfalse.

    Discussion

    Writes the contents of the receiver to the file specified by path (overwriting any existing file at path). path is written in the default C-string encoding if possible (that is, if no information would be lost), in the Unicode encoding otherwise.

    If flag is YEStrue, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path. If flag is NOfalse, the receiver is written directly to path. The YEStrue option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.

    If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • 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 *)url atomically:(BOOL)atomically

    Return Value

    YEStrue if the location is written successfully, otherwise NOfalse.

    Discussion

    If atomically is YEStrue, the receiver is written to an auxiliary location, and then the auxiliary location is renamed to aURL. If atomically is NOfalse, the receiver is written directly to aURL. The YEStrue option guarantees that aURL, if it exists at all, won’t be corrupted even if the system should crash during writing.

    The atomically parameter is ignored if aURL is not of a type that can be accessed atomically.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • 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 *)buffer

    Parameters

    buffer

    Upon return, contains the characters from the receiver. buffer must be large enough to contain all characters in the string ([string length]*sizeof(unichar)).

    Discussion

    Invokes getCharacters:range: with buffer and the entire extent of the receiver as the range.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 4.0.

    See Also

    – length

  • - cString (iOS 2.0)

    Returns a representation of the receiver as a C string in the default C-string encoding.

    Deprecation Statement

    Use cStringUsingEncoding: or UTF8String instead.

    Declaration

    Objective-C

    - (const char *)cString

    Discussion

    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 NSCharacterConversionException if the receiver can’t be represented in the default C-string encoding without loss of information. Use canBeConvertedToEncoding: if necessary to check whether a string can be losslessly converted to the default C-string encoding. If it can’t, use lossyCString or dataUsingEncoding:allowLossyConversion: to get a C-string representation with some loss of information.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • 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 *)lossyCString

    Discussion

    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 iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • 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)cStringLength

    Discussion

    Raises if the receiver can’t be represented in the default C-string encoding without loss of information. You can also use canBeConvertedToEncoding: to check whether a string can be losslessly converted to the default C-string encoding. If it can’t, use lossyCString to get a C-string representation with some loss of information, then check its length explicitly using the ANSI function strlen().

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • - getCString: (iOS 2.0)

    Invokes getCString:maxLength:range:remainingRange: with NSMaximumStringLength as the maximum length, the receiver’s entire extent as the range, and NULL for the remaining range.

    Deprecation Statement

    Use cStringUsingEncoding: or dataUsingEncoding:allowLossyConversion: instead.

    Declaration

    Objective-C

    - (void)getCString:(char *)bytes

    Discussion

    buffer must be large enough to contain the resulting C-string plus a terminating NULL character (which this method adds—[string cStringLength]).

    Raises an NSCharacterConversionException if the receiver can’t be represented in the default C-string encoding without loss of information. Use canBeConvertedToEncoding: if necessary to check whether a string can be losslessly converted to the default C-string encoding. If it can’t, use lossyCString or dataUsingEncoding:allowLossyConversion: to get a C-string representation with some loss of information.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • Invokes getCString:maxLength:range:remainingRange: with maxLength as the maximum length in char-sized units, the receiver’s entire extent as the range, and NULL for the remaining range.

    Deprecation Statement

    Use getCString:maxLength:encoding: instead.

    Declaration

    Objective-C

    - (void)getCString:(char *)bytes maxLength:(NSUInteger)maxLength

    Discussion

    buffer must be large enough to contain maxLength chars plus a terminating zero char (which this method adds).

    Raises an NSCharacterConversionException if the receiver can’t be represented in the default C-string encoding without loss of information. Use canBeConvertedToEncoding: if necessary to check whether a string can be losslessly converted to the default C-string encoding. If it can’t, use lossyCString or dataUsingEncoding:allowLossyConversion: to get a C-string representation with some loss of information.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • 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 *)bytes maxLength:(NSUInteger)maxLength range:(NSRange)aRange remainingRange:(NSRangePointer)leftoverRange

    Discussion

    buffer must be large enough to contain maxLength bytes plus a terminating zero character (which this method adds). Copies and converts as many characters as possible from aRange and stores the range of those not converted in the range given by leftoverRange (if it’s non-nil). Raises an NSRangeException if any part of aRange lies beyond the end of the string.

    Raises an NSCharacterConversionException if the receiver can’t be represented in the default C-string encoding without loss of information. Use canBeConvertedToEncoding: if necessary to check whether a string can be losslessly converted to the default C-string encoding. If it can’t, use lossyCString or dataUsingEncoding:allowLossyConversion: to get a C-string representation with some loss of information.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 2.0.

  • 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

    Swift

    func stringByAddingPercentEscapesUsingEncoding(_ enc: UInt) -> String?

    Objective-C

    - (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding

    Parameters

    encoding

    The 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 encoding to determine the percent escapes necessary to convert the receiver into a legal URL string. Returns nil if encoding cannot 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 CFURLCreateStringByAddingPercentEscapes for more information.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 9.0.

  • Returns a new string made by replacing in the receiver all percent escapes with the matching characters as determined by a given encoding.

    Use stringByRemovingPercentEncoding instead.

    Declaration

    Swift

    func stringByReplacingPercentEscapesUsingEncoding(_ enc: UInt) -> String?

    Objective-C

    - (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding

    Parameters

    encoding

    The 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. Returns nil if the transformation is not possible, for example, the percent escapes give a byte sequence not legal in encoding.

    Discussion

    See CFURLCreateStringByReplacingPercentEscapes for more complex transformations.

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 9.0.

  • Returns the size of the string if it were to be rendered with the specified font on a single line.

    Deprecation Statement

    Use sizeWithAttributes: instead.

    Declaration

    Objective-C

    - (CGSize)sizeWithFont:(UIFont *)font

    Parameters

    font

    The font to use for computing the string size.

    Return Value

    The width and height of the resulting string’s bounding box. These values may be rounded up to the nearest whole number.

    Discussion

    You can use this method to obtain the layout metrics you need to draw a string in your user interface. This method does not actually draw the string or alter the receiver’s text in any way.

    In iOS 6, this method wraps text using the NSLineBreakByWordWrapping option by default. In earlier versions of iOS, this method does not perform any line wrapping and returns the absolute width and height of the string using the specified font.

    Import Statement

    Objective-C

    @import UIKit;

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 7.0.

  • Returns the size of the string if it were to be rendered with the specified font and line attributes on a single line.

    Declaration

    Objective-C

    - (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode

    Parameters

    font

    The font to use for computing the string size.

    width

    The maximum acceptable width for the string. This value is used to calculate where line breaks would be placed.

    lineBreakMode

    The line break options for computing the size of the string. For a list of possible values, see NSLineBreakMode.

    Return Value

    The width and height of the resulting string’s bounding box. These values may be rounded up to the nearest whole number.

    Discussion

    You can use this method to obtain the layout metrics you need to draw a string in your user interface. This method does not actually draw the string or alter the receiver’s text in any way.

    This method returns the width and height of the string constrained to the specified width. Although it computes where line breaks would occur, this method does not actually wrap the text to additional lines. If the size of the string exceeds the given width, this method truncates the text (for layout purposes only) using the specified line break mode until it does conform to the maximum width; it then returns the size of the resulting truncated string.

    Import Statement

    Objective-C

    @import UIKit;

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 7.0.

  • Returns the size of the string if it were rendered with the specified constraints, including a variable font size, on a single line.

    Deprecation Statement

    There is no exact alternative for this method. Human interface guidelines discourage changing the font size this way because it leads to an inconsistent user experience. See UILabel as a possible alternative for some use cases.

    Declaration

    Objective-C

    - (CGSize)sizeWithFont:(UIFont *)font minFontSize:(CGFloat)minFontSize actualFontSize:(CGFloat *)actualFontSize forWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode

    Parameters

    font

    The font to use for computing the string size.

    minFontSize

    The minimum size to which the font may be reduced before resorting to truncation of the text.

    actualFontSize

    On input, a pointer to a floating-point value. On return, this value contains the actual font size that was used to compute the size of the string.

    width

    The maximum acceptable width for the string. This value is used to calculate where line breaks would be placed.

    lineBreakMode

    The line break options for computing the size of the string. For a list of possible values, see NSLineBreakMode.

    Return Value

    The width and height of the resulting string’s bounding box. These values may be rounded up to the nearest whole number.

    Discussion

    You can use this method to obtain the layout metrics you need to draw a string in your user interface. This method does not actually draw the string or alter the receiver’s text in any way.

    Although it computes where line breaks would occur, this method does not actually wrap the text to additional lines. If the entire string does not fit within the given width using the initial font size, this method reduces the font size until the string does fit or until it reaches the specified minimum font size. If it reaches the minimum font size, the method begins truncating the text (for layout purposes only) until the resulting truncated string does fit the width; it then then returns the size of that truncated string.

    Import Statement

    Objective-C

    @import UIKit;

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 7.0.

  • Returns the size of the string if it were rendered and constrained to the specified size.

    Deprecation Statement

    Use boundingRectWithSize:options:attributes:context: instead. See also UILabel as a possible alternative for some use cases.

    Declaration

    Objective-C

    - (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size

    Parameters

    font

    The font to use for computing the string size.

    size

    The maximum acceptable size for the string. This value is used to calculate where line breaks and wrapping would occur.

    Return Value

    The width and height of the resulting string’s bounding box. These values may be rounded up to the nearest whole number.

    Discussion

    You can use this method to obtain the layout metrics you need to draw a string in your user interface. This method does not actually draw the string or alter the receiver’s text in any way.

    This method computes the metrics needed to draw the specified string. This method lays out the receiver’s text and attempts to make it fit the specified size using the specified font and the NSLineBreakByWordWrapping line break option. During layout, the method may break the text onto multiple lines to make it fit better. If the receiver’s text does not completely fit in the specified size, it lays out as much of the text as possible and truncates it (for layout purposes only) according to the specified line break mode. It then returns the size of the resulting truncated string. If the height specified in the size parameter is less than a single line of text, this method may return a height value that is bigger than the one specified.

    Import Statement

    Objective-C

    @import UIKit;

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 7.0.

  • Returns the size of the string if it were rendered with the specified constraints.

    Deprecation Statement

    Use boundingRectWithSize:options:attributes:context: instead.

    Declaration

    Objective-C

    - (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode

    Parameters

    font

    The font to use for computing the string size.

    size

    The maximum acceptable size for the string. This value is used to calculate where line breaks and wrapping would occur.

    lineBreakMode

    The line break options for computing the size of the string. For a list of possible values, see NSLineBreakMode.

    Return Value

    The width and height of the resulting string’s bounding box. These values may be rounded up to the nearest whole number.

    Discussion

    You can use this method to obtain the layout metrics you need to draw a string in your user interface. This method does not actually draw the string or alter the receiver’s text in any way.

    This method computes the metrics needed to draw the specified string. This method lays out the receiver’s text and attempts to make it fit the specified size using the specified font and line break options. During layout, the method may break the text onto multiple lines to make it fit better. If the receiver’s text does not completely fit in the specified size, it lays out as much of the text as possible and truncates it (for layout purposes only) according to the specified line break mode. It then returns the size of the resulting truncated string. If the height specified in the size parameter is less than a single line of text, this method may return a height value that is bigger than the one specified.

    Import Statement

    Objective-C

    @import UIKit;

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 7.0.

  • Draws the string in a single line at the specified point in the current graphics context using the specified font.

    Deprecation Statement

    Use drawAtPoint:withAttributes: instead.

    Declaration

    Objective-C

    - (CGSize)drawAtPoint:(CGPoint)point withFont:(UIFont *)font

    Parameters

    point

    The location (in the coordinate system of the current graphics context) at which to draw the string. This point represents the top-left corner of the string’s bounding box.

    font

    The font to use for rendering.

    Return Value

    The size of the rendered string. The returned values may be rounded up to the nearest whole number.

    Discussion

    This method draws only a single line of text, drawing as much of the string as possible using the given font. This method does not perform any line wrapping during drawing.

    Import Statement

    Objective-C

    @import UIKit;

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 7.0.

  • Draws the string in a single line at the specified point in the current graphics context using the specified font and attributes.

    Deprecation Statement

    Use drawInRect:withAttributes: instead.

    Declaration

    Objective-C

    - (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode

    Parameters

    point

    The location (in the coordinate system of the current graphics context) at which to draw the string. This point represents the top-left corner of the string’s bounding box.

    width

    The maximum width of the string.

    font

    The font to use for rendering.

    lineBreakMode

    The line break options for computing the size of the string. For a list of possible values, see NSLineBreakMode.

    Return Value

    The size of the rendered string. The returned values may be rounded up to the nearest whole number.

    Discussion

    This method draws only a single line of text, drawing as much of the string as possible using the given font and constraints. This method does not perform any line wrapping during drawing.

    If the value in the width parameter is smaller than actual width of the string, truncation may occur. In that situation, the options in the lineBreakMode parameter determine where to end the text.

    Import Statement

    Objective-C

    @import UIKit;

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 7.0.

  • Draws the string in a single line at the specified point in the current graphics context using the specified font and attributes.

    Deprecation Statement

    Use drawInRect:withAttributes: instead.

    Declaration

    Objective-C

    - (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width withFont:(UIFont *)font fontSize:(CGFloat)fontSize lineBreakMode:(NSLineBreakMode)lineBreakMode baselineAdjustment:(UIBaselineAdjustment)baselineAdjustment

    Parameters

    point

    The location (in the coordinate system of the current graphics context) at which to draw the string. This point represents the top-left corner of the string’s bounding box.

    width

    The maximum width of the string.

    font

    The font to use for rendering.

    fontSize

    The font size to use instead of the one associated with the font object in the font parameter.

    lineBreakMode

    The line break options for computing the size of the string. For a list of possible values, see NSLineBreakMode.

    baselineAdjustment

    Specifies the vertical text-adjustment rule to use. This rule is used to determine the position of the text in cases where the text must be drawn at a smaller size.

    Return Value

    The size of the rendered string. The returned values may be rounded up to the nearest whole number.

    Discussion

    This method draws only a single line of text, drawing as much of the string as possible using the given font and constraints. This method does not perform any line wrapping during drawing.

    Import Statement

    Objective-C

    @import UIKit;

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 7.0.

  • Draws the string in a single line with the specified font and attributes, adjusting the font attributes as needed to render as much of the text as possible.

    Deprecation Statement

    Use drawInRect:withAttributes: instead.

    Declaration

    Objective-C

    - (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width withFont:(UIFont *)font minFontSize:(CGFloat)minFontSize actualFontSize:(CGFloat *)actualFontSize lineBreakMode:(NSLineBreakMode)lineBreakMode baselineAdjustment:(UIBaselineAdjustment)baselineAdjustment

    Parameters

    point

    The location (in the coordinate system of the current graphics context) at which to draw the string. This point represents the top-left corner of the string’s bounding box.

    width

    The maximum width of the string.

    font

    The font to use for rendering.

    minFontSize

    The minimum size to which the font may be reduced before resorting to truncation of the text.

    actualFontSize

    On input, a pointer to a floating-point value. On return, this value contains the actual font size that was used to render the string.

    lineBreakMode

    The line break options for computing the size of the string. For a list of possible values, see NSLineBreakMode.

    baselineAdjustment

    Specifies the vertical text-adjustment rule to use. This rule is used to determine the position of the text in cases where the text must be drawn at a smaller size.

    Return Value

    The size of the rendered string. The returned values may be rounded up to the nearest whole number.

    Import Statement

    Objective-C

    @import UIKit;

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 7.0.

  • Draws the string in the current graphics context using the specified bounding rectangle and font.

    Deprecation Statement

    Use drawInRect:withAttributes: instead.

    Declaration

    Objective-C

    - (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font

    Parameters

    rect

    The bounding rectangle (in the current graphics context) in which to draw the string.

    font

    The font to use for rendering.

    Return Value

    The size of the rendered string. The returned values may be rounded up to the nearest whole number.

    Discussion

    This method draws as much of the string as possible using the given font and constraints. This method uses the UILineBreakModeWordWrap line break mode and the UITextAlignmentLeft alignment.

    Import Statement

    Objective-C

    @import UIKit;

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 7.0.

  • Draws the string in the current graphics context using the specified bounding rectangle, font, and attributes.

    Deprecation Statement

    Use drawInRect:withAttributes: instead.

    Declaration

    Objective-C

    - (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode

    Parameters

    rect

    The bounding rectangle (in the current graphics context) in which to draw the string.

    font

    The font to use for rendering.

    lineBreakMode

    The line break options for computing the size of the string. For a list of possible values, see NSLineBreakMode.

    Return Value

    The size of the rendered string. The returned values may be rounded up to the nearest whole number.

    Discussion

    This method draws as much of the string as possible using the given font, line break mode, and size constraints. The text is drawn using the UITextAlignmentLeft alignment.

    Import Statement

    Objective-C

    @import UIKit;

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 7.0.

  • Draws the string in the current graphics context using the specified bounding rectangle, font and attributes.

    Deprecation Statement

    Use drawInRect:withAttributes: instead.

    Declaration

    Objective-C

    - (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode alignment:(NSTextAlignment)alignment

    Parameters

    rect

    The bounding rectangle (in the current graphics context) in which to draw the string.

    font