Brief Intro to Strings of Foundation Framework

Strings

The Foundation Framework includes a set of APIs used to manipulate character strings. The operations supported by these classes include:

  • Creating, converting, and formatting strings
  • Reading and writing strings to/from a file or resource
  • String query, sorting, and comparison

In Objective-C a string is represented as an object. This means that strings can be used wherever other objects can be used (in collections, etc.). Each string object is composed of an array of Unicode (i.e., text) characters. The Foundation Framework NSString and NSMutableString classes provide the APIs for string objects. The classes NSAttributedString andNSMutableAttributedString manage strings that have associated attributes (e.g., font, paragraph style, foreground color, etc.). The attributes are identified by name and stored in a Foundation Framework NSDictionary object.

Note   NSString and NSMutableString are members of the NSString class cluster. Theclass cluster design pattern is used extensively in the Foundation Framework for grouping a number of related classes with a common base interface. Likewise,NSAttributedString and NSMutableAttributedString are members of theNSAttributeString class cluster. In the case of these two class clusters, the mutable class of each pair declares additional methods that allow their (string) contents to be modified.

This family of classes supports the creation of immutable and mutable string objects, attributed strings, and Unicode characters.

NSString

NSString and NSMutableString provide the APIs for Objective-C objects that manage strings. TheNSString class manages immutable strings, strings that are defined when they are created and, subsequently, can’t be changed. NSMutableString is the mutable (its contents can be edited) subclass of NSString.

NSMutableString adds methods above those defined by its superclass (NSString) to create and initialize a (mutable) string, and to modify a string.

Creation and Initialization

The NSString class defines numerous methods for creating and initializing strings. The NSString init method returns an initialized NSString object with no characters. The NSString class also defines numerous initializers with parameters. These methods all begin with init and enable you to initialize an NSString object with characters, a byte buffer, contents of a file, contents of a URL, a C string, a UTF8 string, and so forth.

Scanning Values

The NSString class contains numerous methods for retrieving a primitive value from a string object. These methods support basic primitives (i.e., intfloat, etc.) and the Foundation FrameworkNSInteger type. These methods follow a naming convention whereby the return type forms the prefix of the method name. The corresponding method signatures are shown in Listing 10-2.

Listing 10-2.  NSString Methods for Retrieving Primitive Values

- (int) intValue;
- (float) floatValue;
- (double) doubleValue;
- (long long) longLongValue;
- (bool) boolValue;
- (NSInteger) integerValue;

The following example returns a result of type int assigned to the variable myValue for the string"17".

int myValue = [@"17" intValue];

Each of these methods returns a value of 0 if the string doesn’t begin with a valid decimal text representation of a number. Also note that these methods don’t support localization. The Foundation Framework NSScanner class provides additional functionality (including localization) for reading and converting NSString objects into numeric and string values. The following code fragment uses theNSScanner class to set the variable myValue (of type int) for the string "17".

NSScanner *scanner = [NSScanner scannerWithString:@"17"];
BOOL success = [scanner scanInt:&myValue];

The NSScanner scanInt: method returns a BOOL value of YES if the scanned string is numeric; if it returns NO, then the value stored in the variable myValue is not valid.

String Search and Comparison

The NSString class includes several methods to search for a substring within a string object. TherangeOfString: methods each return a range that identifies the first occurrence of an input string within the receiver object. The returned value is an NSRange instance, a Foundation Framework data type used to describe a portion of a series. NSRange is defined as a structure with two elements:

  • location: An NSUInteger that specifies the start of the range.
  • length: An NSUInteger that specifies the length of the range.

The following code fragment returns an NSRange instance assigned to the variable worldRange that identifies the first occurrence of the string "World" within the string "Hello, World!".

NSString *greeting = @"Hello, World!";
NSRange worldRange = [greeting rangeWithString:@"World"];

In the preceding example, the elements of worldRange have the values six (location) and 5 (length). Several of the rangeOfString: methods provide additional parameters that enable you to specify string comparison options, the range within the receiver object to search, and the locale to use for the search.

The NSString rangeOfCharacterFromSet: methods also perform range-based searches. They differ from the rangeOfString: methods in that they return a range that specifies the location (in the receiver string) of the first character found from a given character set. The character set input parameter is of type NSCharacterSet, a set of (Unicode-compliant) characters. The following code fragment returns an NSRange instance that identifies the first occurrence of a punctuation symbol (e.g., period, exclamation point, etc.) within the string "Hello, World!".

NSCharacterSet *chars = [NSCharacterSet punctuationCharacterSet];
NSRange charRange = [@"Hello, World!" rangeOfCharacterFromSet:chars];

In the preceding example, the elements of charRange have the values eleven (location) and 1 (length). As with the rangeOfString: methods, the rangeOfCharacterFromSet: methods provide additional parameters that enable you to specify string comparison options, and the range within the receiver object to search.

The NSString stringByReplacingOccurrencesOfString:withString: methods create a new string from an existing string, with all occurrences of a target (input) string in the receiver replaced by another (input) string. The following code fragment takes an initial string, "Hello, World!", and returns a new string, "Hello, Earthlings!", using this method.

NSString *greeting = @"Hello, World!";
NSString *newGreeting = [greeting stringByReplacingOccurrencesOfString:@"World!"
                         withString:@"Earthlings!"];

The NSString class contains several methods to compare a string to another string. The compare:methods return an NSComparisonResult instance, a Foundation Framework data type used to indicate how the items in a comparison are ordered a portion of a series. NSComparisonResult is defined as an enum with three constants:

  • NSOrderedAscending: The left operand is less than the right.
  • NSOrderedSame: The operands are equal.
  • NSOrderedDescending: The left operand is greater than the right.

The following statement returns an NSComparisonResult assigned to the variable order that identifies the result of the ordered comparison between the strings "cat" and "dog".

NSComparisonResult order = [@"cat" compare:@"dog"];

The result of this comparison is NSOrderedAscending, indicating that the word cat is alphabetically ordered before the word dogNSString contains additional comparison methods that enable you to perform localized comparisons, case insensitive comparisons, and other options.

String I/O

NSString includes methods for both reading and writing a string to/from a file or a URL. ThewriteToFile:atomically:encoding:error: method writes a string to a file at the specified path. This method also specifies the encoding to use if the file is written atomically (to prevent the file from being corrupted if the system crashes while the file is being written), and an error object that describes the problem if an error occurs while writing the file. The method returns YES if the string is written to the file successfully. The writeToURL:atomically:encoding:error: method writes a string to a given URL. The NSString stringWithContentsOfFile:stringWithContentsOfURL:,initWithContentsOfFile:, and initWithContentsOfURL: methods create and initialize a string from a file or URL.

Introspection

The NSString class includes numerous methods for obtaining information about an NSString object. The following statement uses the NSString length method to retrieve the number of characters in the string "Hello, World!".

int len = [@"Hello, World!" length];

The following statement uses the NSString hasPrefix: method to return a Boolean value indicating whether the "Hello, World!" string has a prefix of "Hello".

BOOL hasPrefix = [@"Hello, World!" hasPrefix:@"Hello"];

Modifying a String

NSMutableString adds several methods to those provided by NSString for modifying a string. These methods enable you to append a string or a format string, to insert or delete characters in a string, to replace characters or a string within a string, or to set a string to a new value. The following code fragment creates a mutable string named "Hello" and then appends the string,"World!" to it.

NSMutableString *mgreet = [@"Hello" mutableCopy];
[mgreet appendString:@", World!"];

NSAttributedString

NSAttributedString and NSMutableAttributedString provide the APIs for Objective-C objects that manage strings and associated sets of attributes. The NSAttributedString class managesimmutable strings, while the NSMutableAttributedString class manages mutable strings.

The methods provided for the NSAttributedString class enable the creation and initialization of strings, retrieval of string and attribute information, and enumerating over attributes in a string using a block object. The initWithString:attributes: method initializes an NSAttributeStringinstance with attributes, where the attributes are provided in an NSDictionary instance. The following code fragment creates and initializes an NSAttributedString with the string "Hello" and a single attribute (locale = en-US).

NSDictionary *attrs = @{@"locale":@"en-US"};
NSAttributedString *greeting = [[NSAttributedString alloc] initWithString:@"Hello"
                                                               attributes:attrs];

The next statement retrieves the value of the attribute (using the key "locale") from the attribute string and also sets the range of the attribute to the variable of type NSRange named range.

NSRange range;
id value = [greeting attribute:@"locale" atIndex:0 effectiveRange:&range];

NSString Literals

Objective-C provides language-level support for creating NSString literals using the @ symbol followed by a text string enclosed in double-quotes. The following statement creates an NSStringobject named book using an NSString literal.

NSString *book = @"Pro Objective-C";

NSString literals are compile-time constants. They are allocated at compile time and exist for the lifetime of the program.

Format Strings

The NSString class includes several methods for formatting string objects using a format string that is composed of ordinary text characters and zero or more format specifiers. A format specifier is a specification for converting an argument in a format string to a character string. Each format specifier begins with a % character that specifies a placeholder for an argument value, immediately followed by a character sequence that indicates the type of the argument. The list of format specifiers supported by the NSString formatting methods include those defined by the IEEE printf specification along with the format specifier '%@', which is used to format an Objective-C object. For example, the format string @"%d" expects an argument of integer type to be substituted for the format string. The NSString stringWithFormat: method and other related methods create and initialize NSString objects using format strings. The syntax for the stringWithFormat method is

+ (id)stringWithFormat:(NSString *)format, ...

Where format is the format string and ... specifies the comma-separated list of argument(s) to substitute into the format. The following example creates an NSString object assigned to the variable magicNumber with the text "Your number is 17".

NSString *magicNumber = [NSString stringWithFormat: @"Your number is %d", 17];

In this example the format string, @"Your number is %d", contains ordinary text and a single format specifier, %d, that is substituted for the argument 17. The next example creates a string formatted using the NSString object magicNumber.

NSString *description = [NSString stringWithFormat:
                         @"Description is %@", magicNumber];

The %@ format specifier substitutes the string returned by invoking either thedescriptionWithLocale: (if available) or description method on the object.

The Foundation Framework includes several classes (NSFormatterNSDateFormatter,NSNumberFormatter) that provide additional functionality for interpreting and creating NSStringobjects that represent other values.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值