Class: NSString
Overview
The NSString class declares the programmatic interface for an object that manages immutable strings. An immutable string is a text string that is defined when it is created and subsequently cannot be changed. NSString is implemented to represent an array of Unicode characters, in other words, a text string.
Direct Known Subclasses
Class Method Summary (collapse)
-
+ availableStringEncodings
Returns a zero-terminated list of the encodings string objects support in the application’s environment.
-
+ defaultCStringEncoding
Returns the C-string encoding assumed for any method accepting a C string as an argument.
-
+ localizedNameOfStringEncoding:
Returns a human-readable string giving the name of a given encoding.
-
+ localizedStringWithFormat:
Returns a string created by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale.
-
+ pathWithComponents:
Returns a string built from the strings in a given array by concatenating them with a path separator between each pair.
-
+ string
Returns an empty string.
-
+ stringWithCharacters:length:
Returns a string containing a given number of characters taken from a given C array of Unicode characters.
-
+ stringWithContentsOfFile:encoding:error:
Returns a string created by reading data from the file at a given path interpreted using a given encoding.
-
+ stringWithContentsOfFile:usedEncoding:error:
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.
-
+ stringWithContentsOfURL:encoding:error:
Returns a string created by reading data from a given URL interpreted using a given encoding.
-
+ stringWithContentsOfURL:usedEncoding:error:
Returns a string created by reading data from a given URL and returns by reference the encoding used to interpret the data.
-
+ stringWithCString:encoding:
Returns a string containing the bytes in a given C array, interpreted according to a given encoding.
-
+ stringWithFormat:
Returns a string created by using a given format string as a template into which the remaining argument values are substituted.
-
+ stringWithString:
Returns a string created by copying the characters from another given string.
-
+ stringWithUTF8String:
Returns a string created by copying the data from a given C array of UTF8-encoded bytes.
Instance Method Summary (collapse)
-
- boolValue
Returns the Boolean value of the receiver’s text.
-
- canBeConvertedToEncoding:
Returns a Boolean value that indicates whether the receiver can be converted to a given encoding without loss of information.
-
- capitalizedString
Returns a capitalized representation of the receiver.
-
- capitalizedStringWithLocale:
Returns a capitalized representation of the receiver using the specified locale.
-
- caseInsensitiveCompare:
Returns the result of invoking compare:options: with NSCaseInsensitiveSearch as the only option.
-
- characterAtIndex:
Returns the character at a given array position.
-
- commonPrefixWithString:options:
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.
-
- compare:
Returns the result of invoking compare:options:range: with no options and the receiver’s full extent as the range.
-
- compare:options:
Returns the result of invoking compare:options:range: with a given mask as the options and the receiver’s full extent as the range.
-
- compare:options:range:
Returns the result of invoking compare:options:range:locale: with a nil locale.
-
- compare:options:range:locale:
Returns an NSComparisonResult value that indicates the lexical ordering of a specified range within the receiver and a given string.
-
- completePathIntoString:caseSensitive:matchesIntoArray:filterTypes:
Interprets the receiver as a path in the file system and attempts to perform filename completion, returning a numeric value that indicates whether a match was possible, and by reference the longest path that matches the receiver.
-
- componentsSeparatedByCharactersInSet:
Returns an array containing substrings from the receiver that have been divided by characters in a given set.
-
- componentsSeparatedByString:
Returns an array containing substrings from the receiver that have been divided by a given separator.
-
- cStringUsingEncoding:
Returns a representation of the receiver as a C string using a given encoding.
-
- dataUsingEncoding:
Returns an NSData object containing a representation of the receiver encoded using a given encoding.
-
- dataUsingEncoding:allowLossyConversion:
Returns an NSData object containing a representation of the receiver encoded using a given encoding.
-
- decomposedStringWithCanonicalMapping
Returns a string made by normalizing the receiver’s contents using Form D.
-
- decomposedStringWithCompatibilityMapping
Returns a string made by normalizing the receiver’s contents using Form KD.
-
- description
Returns the receiver.
-
- doubleValue
Returns the floating-point value of the receiver’s text as a double.
-
- encode
on RubyStrings.
- - encode!
-
- enumerateLinesUsingBlock:
Enumerates all the lines in a string.
-
- enumerateLinguisticTagsInRange:scheme:options:orthography:usingBlock:
Performs linguistic analysis on the specified string by enumerating the specific range of the string, providing the Block with the located tags.
-
- enumerateSubstringsInRange:options:usingBlock:
Enumerates the substrings of the specified type in the specified range of the string.
-
- fastestEncoding
Returns the fastest encoding to which the receiver may be converted without loss of information.
-
- fileSystemRepresentation
Returns a file system-specific representation of the receiver.
-
- floatValue
Returns the floating-point value of the receiver’s text as a float.
-
- getBytes:maxLength:usedLength:encoding:options:range:remainingRange:
Gets a given range of characters as bytes in a specified encoding.
-
- getCharacters:range:
Copies characters from a given range in the receiver into a given buffer.
-
- getCString:maxLength:encoding:
Converts the receiver’s content to a given encoding and stores them in a buffer.
-
- getFileSystemRepresentation:maxLength:
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.
-
- getLineStart:end:contentsEnd:forRange:
Returns by reference the beginning of the first line and the end of the last line touched by the given range.
Methods inherited from NSObject
#!, #!=, #!~, #, #==, #===, #=~, #Rational, #__callee__, #__method__, #__send__, #__type__, `, alloc, allocWithZone:, #autoContentAccessingProxy, autoload, autoload?, autorelease_pool, #awakeAfterUsingCoder:, binding, block_given?, caller, cancelPreviousPerformRequestsWithTarget:, cancelPreviousPerformRequestsWithTarget:selector:object:, catch, class, classFallbacksForKeyedArchiver, #classForCoder, #classForKeyedArchiver, classForKeyedUnarchiver, #clone, conformsToProtocol:, #copy, copyWithZone:, #dealloc, #define_singleton_method, description, display, #doesNotRecognizeSelector:, #dup, #enum_for, #eql?, #equal?, #extend, fail, #finalize, format, #forwardInvocation:, #forwardingTargetForSelector:, framework, #freeze, #frozen?, getpass, gets, global_variables, #init, initialize, #initialize_clone, #initialize_copy, #initialize_dup, #inspect, instanceMethodForSelector:, instanceMethodSignatureForSelector:, #instance_eval, #instance_exec, #instance_of?, #instance_variable_defined?, #instance_variable_get, #instance_variable_set, #instance_variables, instancesRespondToSelector:, isSubclassOfClass:, #is_a?, iterator?, #kind_of?, lambda, load, load_bridge_support_file, load_plist, local_variables, loop, #method, #methodForSelector:, #methodSignatureForSelector:, #methods, #mutableCopy, mutableCopyWithZone:, new, #nil?, open, p, #performSelector:onThread:withObject:waitUntilDone:, #performSelector:onThread:withObject:waitUntilDone:modes:, #performSelector:withObject:afterDelay:, #performSelector:withObject:afterDelay:inModes:, #performSelectorInBackground:withObject:, #performSelectorOnMainThread:withObject:waitUntilDone:, #performSelectorOnMainThread:withObject:waitUntilDone:modes:, print, printf, #private_methods, proc, #protected_methods, #public_method, #public_methods, #public_send, putc, puts, raise, rand, readline, readlines, #replacementObjectForCoder:, #replacementObjectForKeyedArchiver:, require, resolveClassMethod:, resolveInstanceMethod:, #respond_to?, #respond_to_missing?, select, #send, setVersion:, #singleton_methods, sprintf, srand, superclass, #taint, #tainted?, #tap, test, throw, #to_plist, #to_s, trace_var, trap, #trust, #untaint, untrace_var, #untrust, #untrusted?, version
Constructor Details
This class inherits a constructor from NSObject
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class NSObject
Class Method Details
+ (const NSStringEncoding) availableStringEncodings
Returns a zero-terminated list of the encodings string objects support in the application’s environment. Among the more commonly used encodings are: NSASCIIStringEncoding NSUnicodeStringEncoding NSISOLatin1StringEncoding NSISOLatin2StringEncoding NSSymbolStringEncodingSee the “Constants” section for a larger list and descriptions of many supported encodings. In addition to those encodings listed here, you can also use the encodings defined for CFString in Core Foundation; you just need to call the CFStringConvertEncodingToNSStringEncoding function to convert them to a usable format.
+ (NSStringEncoding) defaultCStringEncoding
Returns the C-string encoding assumed for any method accepting a C string as an argument. This method returns a user-dependent encoding who value is derived from user’s default language and potentially other factors. You might sometimes need to use this encoding when interpreting user documents with unknown encodings, in the absence of other hints, but in general this encoding should be used rarely, if at all. Note that some potential values might result in unexpected encoding conversions of even fairly straightforward NSString content—for example, punctuation characters with a bidirectional encoding.Methods that accept a C string as an argument use …CString… in the keywords for such arguments: for example, stringWithCString:—note, though, that these are deprecated. The default C-string encoding is determined from system information and can’t be changed programmatically for an individual process. See “String Encodings” for a full list of supported encodings.
+ (String) localizedNameOfStringEncoding(encoding)
Returns a human-readable string giving the name of a given encoding.
+ (Object) localizedStringWithFormat(format, ...)
Returns a string created by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale. This method is equivalent to using initWithFormat:locale: and passing [[NSUserDefaults standardUserDefaults] dictionaryRepresentation] as the locale argument.As an example of formatting, this method replaces the decimal according to the locale in %f and %d substitutions, and calls descriptionWithLocale: instead of description where necessary.This code excerpt creates a string from another string and a float: The resulting string has the value “Cost: 1234.560000n” if the locale is en_US, and “Cost: 1234,560000n” if the locale is fr_FR.See “Formatting String Objects” for more information.
+ (String) pathWithComponents(components)
Returns a string built from the strings in a given array by concatenating them with a path separator between each pair. This method doesn’t clean up the path created; use stringByStandardizingPath to resolve empty components, references to the parent directory, and so on.
+ (Object) string
Returns an empty string.
+ (Object) stringWithCharacters(chars, length:length)
Returns a string containing a given number of characters taken from a given C array of Unicode characters.
+ (Object) stringWithContentsOfFile(path, encoding:enc, error:error)
Returns a string created by reading data from the file at a given path interpreted using a given encoding.
+ (Object) stringWithContentsOfFile(path, usedEncoding:enc, error:error)
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. This method attempts to determine the encoding of the file at path.
+ (Object) stringWithContentsOfURL(url, encoding:enc, error:error)
Returns a string created by reading data from a given URL interpreted using a given encoding.
+ (Object) stringWithContentsOfURL(url, usedEncoding:enc, error:error)
Returns a string created by reading data from a given URL and returns by reference the encoding used to interpret the data. This method attempts to determine the encoding at url.
+ (Object) stringWithCString(cString, encoding:enc)
Returns a string containing the bytes in a given C array, interpreted according to a given encoding. If cString is not a NULL-terminated C string, or encoding does not match the actual encoding, the results are undefined.
+ (Object) stringWithFormat(format, ...)
Returns a string created by using a given format string as a template into which the remaining argument values are substituted. This method is similar to localizedStringWithFormat:, but using the canonical locale to format numbers. 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.
+ (Object) stringWithString(aString)
Returns a string created by copying the characters from another given string.
+ (Object) stringWithUTF8String(bytes)
Returns a string created by copying the data from a given C array of UTF8-encoded bytes.
Instance Method Details
- (Boolean) boolValue
Returns the Boolean value of the receiver’s text. The method 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.
- (Boolean) canBeConvertedToEncoding(encoding)
Returns a Boolean value that indicates whether the receiver can be converted to a given encoding without loss of information. 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.
- (String) capitalizedString
Returns a capitalized representation of the receiver. A “word” here is any sequence of characters delimited by spaces, tabs, or line terminators (listed under getLineStart:end:contentsEnd:forRange:). Other common word delimiters such as hyphens and other punctuation aren’t considered, so this method 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.Note: This method performs the canonical (non-localized) mapping. It is suitable for programming operations that require stable results not depending on the user’s locale preference. For localized case mapping for strings presented to users, use the capitalizedStringWithLocale: method.
- (String) capitalizedStringWithLocale(locale)
Returns a capitalized representation of the receiver using the specified locale. For the user preference locale setting, pass the result of the NSLocale method currentLocale.
- (NSComparisonResult) caseInsensitiveCompare(aString)
Returns the result of invoking compare:options: with NSCaseInsensitiveSearch as the only option. If you are comparing strings to present to the end-user, you should typically use localizedCaseInsensitiveCompare: instead.
- (Integer) characterAtIndex(index)
Returns the character at a given array position. Raises an NSRangeException if index lies beyond the end of the receiver.
- (String) commonPrefixWithString(aString, options:mask)
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. 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”.
- (NSComparisonResult) compare(aString)
Returns the result of invoking compare:options:range: with no options and the receiver’s full extent as the range. If you are comparing strings to present to the end-user, you should typically use localizedCompare: or localizedCaseInsensitiveCompare: instead.
- (NSComparisonResult) compare(aString, options:mask)
Returns the result of invoking compare:options:range: with a given mask as the options and the receiver’s full extent as the range. If you are comparing strings to present to the end-user, you should typically use localizedCompare: or localizedCaseInsensitiveCompare: instead, or use compare:options:range:locale: and pass the user’s locale.
- (NSComparisonResult) compare(aString, options:mask, range:range)
Returns the result of invoking compare:options:range:locale: with a nil locale. If you are comparing strings to present to the end-user, you should typically use compare:options:range:locale: instead and pass the user’s locale (currentLocale [NSLocale]).
- (NSComparisonResult) compare(aString, options:mask, range:range, locale:locale)
Returns an NSComparisonResult value that indicates the lexical ordering of a specified range within the receiver and a given string.
- (Integer) completePathIntoString(outputName, caseSensitive:flag, matchesIntoArray:outputArray, filterTypes:filterTypes)
Interprets the receiver as a path in the file system and attempts to perform filename completion, returning a numeric value that indicates whether a match was possible, and by reference the longest path that matches the receiver. 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).
- (Array) componentsSeparatedByCharactersInSet(separator)
Returns an array containing substrings from the receiver that have been divided by characters in a given set. 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.
- (Array) componentsSeparatedByString(separator)
Returns an array containing substrings from the receiver that have been divided by a given separator. 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: produces an array { @“Norman”, @“Stanley”, @“Fletcher” }.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, “Norman”—the array contains the string itself, in this case { @“Norman” }.
- (const char) cStringUsingEncoding(encoding)
Returns a representation of the receiver as a C string using a given encoding. The returned C string is guaranteed to be valid only until either the receiver is freed, or until the current autorelease pool 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).
- (NSData) dataUsingEncoding(encoding)
Returns an NSData object containing a representation of the receiver encoded using a given encoding.
- (NSData) dataUsingEncoding(encoding, allowLossyConversion:flag)
Returns an NSData object containing a representation of the receiver encoded using a given encoding. If flag is YES and the receiver can’t be converted without losing some information, some characters may be removed or altered in conversion. For example, in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding, the character ‘Á’ becomes ‘A’, losing the accent.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.
- (String) decomposedStringWithCanonicalMapping
Returns a string made by normalizing the receiver’s contents using Form D.
- (String) decomposedStringWithCompatibilityMapping
Returns a string made by normalizing the receiver’s contents using Form KD.
- (String) description
Returns the receiver.
- (Float) doubleValue
Returns the floating-point value of the receiver’s text as a double. This method skips any whitespace at the beginning of the string. This method uses formatting information stored in the non-localized value; use an NSScanner object for localized scanning of numeric values from a string.
- (Object) encode
on RubyStrings.
- (Object) encode!
- (Object) enumerateLinesUsingBlock(block)
Enumerates all the lines in a string.
- (Object) enumerateLinguisticTagsInRange(range, scheme:tagScheme, options:opts, orthography:orthography, usingBlock:block)
Performs linguistic analysis on the specified string by enumerating the specific range of the string, providing the Block with the located tags. This is a convenience method. It is the equivalent of creating an instance of NSLinguisticTagger, specifying the receiver as the string to be analyzed, and the orthography (or nil) and then invoking the NSLinguisticTagger method or enumerateTagsInRange:scheme:options:usingBlock:.
- (Object) enumerateSubstringsInRange(range, options:opts, usingBlock:block)
Enumerates the substrings of the specified type in the specified range of the string. 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".
- (NSStringEncoding) fastestEncoding
Returns the fastest encoding to which the receiver may be converted without loss of information. “Fastest” applies to retrieval of characters from the string. This encoding may not be space efficient.
- (const char) fileSystemRepresentation
Returns a file system-specific representation of the receiver. 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 autorelease context in which the representation is created.Raises an NSCharacterConversionException if the receiver can’t be represented in the file system’s encoding. It also raises an exception if the string 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 NSFileManager‘s stringWithFileSystemRepresentation:length: method.
- (Float) floatValue
Returns the floating-point value of the receiver’s text as a float. This method uses formatting information stored in the non-localized value; use an NSScanner object for localized scanning of numeric values from a string.
- (Boolean) getBytes(buffer, maxLength:maxBufferCount, usedLength:usedBufferCount, encoding:encoding, options:options, range:range, remainingRange:leftover)
Gets a given range of characters as bytes in a specified encoding. Conversion might stop when the buffer fills, but it might also stop when the conversion isn't possible due to the chosen encoding.
- (Object) getCharacters(buffer, range:aRange)
Copies characters from a given range in the receiver into a given buffer. 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.
- (Boolean) getCString(buffer, maxLength:maxBufferCount, encoding:encoding)
Converts the receiver’s content to a given encoding and stores them in a buffer. 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).
- (Boolean) getFileSystemRepresentation(buffer, maxLength:maxLength)
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. 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.
- (Object) getLineStart(startIndex, end)
Returns by reference the beginning of the first line and the end of the last line touched by the given range. A line is delimited by any of these characters, the longest possible sequence being preferred to any shorter:U+000D (r or CR) U+2028 (Unicode line separator) U+000A (n or LF) U+2029 (Unicode paragraph separator) rn, 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.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.