- 浏览: 39861 次
- 性别:
- 来自: 北京
最近访客 更多访客>>
文章分类
最新评论
-
chenniaoc:
http://www.techotopia.com/index ...
objective-c NSString 使用详细指南
Declaring Constant String Objects
A constant string object is declared by encapsulating the string in double quotes (") preceded by an @ sign. For example:
@"This is a constant character string object";
In order to display the current value of a string object using NSLog, simply reference the string using '%@' as follows:
NSLog (@"%@", @"This is a constant character string object");
Even though all we are doing here is creating a constant string object, keep in mind that this is still an object. As such, it has a range of methods that we can call on it. For example string objects have a length method that returns the number of characters in the string. We can, therefore, call this on a constant string object:
int len = [@"Hello" length]; NSLog (@"Length of string = %i", len);
The above code declares a constant string object containing the word "Hello" and calls the length method of object. The result is assigned to an integer variable named len which in turn is displayed using NSLog. When compiled and executed, we get the following output:
Length of string = 5
Constant string objects are actually instantiated from the NSConstantString class which, much like the other classes we will look at in this chapter, is actually a subclass of the NSString class. In practice, given the way that constant strings are used, it is unlikely that you will need to specifically declare your string constants as being of type NSConstantString. It is more likely that you will declare the string as we have done in this section and let the compiler handle the rest.
[edit ] Creating Mutable and Immutable String Objects
Two additional types of Objective-C string objects are mutable and immutable . When you create a string object of type NSString you are creating an immutable string object. This means that once a string has been assigned to the object, that string cannot subsequently be modified in any way.
NSString *string1 = @"This string is immutable";
Mutable string objects, on the other hand, are declared using the NSMutableString class and allow the string contained within the object to be modified using a variety of methods (some of which will be covered in the remainder of this chapter). NSMutableString is a subclass of NSString, which in turn is a subclass of NSObject. Mutable strings cannot be initialized simply by assigning a constant string object as we did above since that will just give us a pointer to an immutable constant string object. Instead, the string constant must be copied into the mutable string object. For example:
NSMutableString *string2 = [NSMutableString stringWithString:@"This string is mutable"];
Once a string has been declared as immutable, the only way to get a mutable version of the string is to create a mutable string object and copy the contents of the immutable string object to it. This can be achieved using the NSMutableString stringWithString class method. For example:
NSString *string1 = @"This is a string"; NSMutableString *string2; string2 = [NSMutableString stringWithString: string1];
Once executed, the above code will create an immutable string object (string1) initialized with the text "This is a string" and an empty pointer to an immutable string object (string2). The stringWithString class method of the NSMutableString class is then called, passing though the immutable string1 as an argument. This method returns a new object containing the immutable string and assigns it to string2. We now have a mutable copy of the immutable string1 object.
[edit ] Getting the Length of a String
The length of the string in a string object can be obtained by accessing the length method of the string object:
NSString *string1 = @"This string is Immutable"; int len = [string1 length]; NSLog (@"String length is %i", len);
The above code fragment will produce the following output when executed:
String length is 24
[edit ] Copying a String
When copying one string object to another it might be tempting to think that you can simply assign the object from one variable to another. For example, if we had two integer variables and wanted to assign the value of one to the other we could simply do the following:
int a = 10; int b; a = b;
After the above code has executed, both variables a and b will contain the value 10 . The same is not, however, true of string objects. Take for example the following code fragment:
NSMutableString *string1; NSMutableString *string2; string1 = [NSMutableString stringWithString: @"This is a string"]; string2 = string1;
What we have achieved here is to create two variables (string1 and string2) that point to the memory location of the same string object. This is because the '*' before the variable names in the declarations indicates that this is a pointer to an object, not an actual object. Any time that we access the object referenced by either of these pointers we will, in fact, be accessing the same object. To prove this, we can make a change using the string2 reference and then display the string associated with both the string1 and string1 object pointers:
NSMutableString *string1; NSMutableString *string2; string1 = [NSMutableString stringWithString: @"This is a string"]; string2 = string1; [string2 appendString: @" and it is mine!"]; NSLog (@"string1 = %@", string1); NSLog (@"string2 = %@", string2);
The above code will display the following output, proving that both string1 and string2 point to the same object since only one reference was modified, yet both show the change:
2009-11-03 14:35:37.731 t[32239:10b] string1 = This is a string and it is mine! 2009-11-03 14:35:37.732 t[32239:10b] string2 = This is a string and it is mine!
To actually copy one string object to another string object we must use stringWithString method the NSMutableString class:
NSMutableString *string1; NSMutableString *string2; string1 = [NSMutableString stringWithString: @"This is a string"]; // Initialize string1 string2 = [NSMutableString stringWithString: string1]; // Copy string1 object to string2 [string2 appendString: @" and it is mine!"]; // Modify string2 NSLog (@"string1 = %@", string1); NSLog (@"string2 = %@", string2);
When executed, the appended text appears only in the object referenced by string2 since string2 now references a different object to that referenced by string1:
2009-11-03 14:42:10.426 t[32263:10b] string1 = This is a string 2009-11-03 14:42:10.427 t[32263:10b] string2 = This is a string and it is mine!
[edit ] Searching for a Substring
A common requirement when working with strings is to identify whether a particular sequence of characters appears within a string. This can be achieved using the rangeOfString method. This method returns a structure of type NSRange . The NSRange structure contains a location value providing the index into the string of the matched substring and a length value indicating the length of the match.
NSString *string1 = @"The quick brown fox jumped"; NSRange match; match = [string1 rangeOfString: @"brown fox"]; NSLog (@"match found at index %i", match.location); NSLog (@"match length = %i", match.length);
The NSLog call will display the location and length of the match. Note that the location is an index into the string where the match started and that the index considers the first position in a string to be 0 and not 1. As such, the location in our example will be 10 and the length will be 9.
In the event that no match is found, the rangeOfString method will set the location member of the NSRange structure to NSNotFound . For example:
NSString *string1 = @"The quick brown fox jumped"; NSRange match; match = [string1 rangeOfString: @"brown dog"]; if (match.location == NSNotFound) NSLog (@"Match not found"); else NSLog (@"match found at index %i", match.location);
[edit ] Replacing Parts of a String
Sections of a mutable string may be replaced by other character sequences using the replaceCharactersInRange method. This method directly modifies the string object on which the method is called so only works on mutable string objects.
This method requires two arguments. The first argument is an NSRange structure consisting of the location of the first character and the total number of characters to be replaced. The second argument is the replacement string. An NSRange structure can be created by calling NSMakeRange and passing though the location and length values as arguments. For example, to replace the word "fox" with "squirrel" in our sample mutable string object we would write the following Objective-C code:
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"]; [string1 replaceCharactersInRange: NSMakeRange(16, 3) withString: @"squirrel"]; NSLog (@"string1 = %@", string1);
As you may have noted from the above example, the replacement string does not have to be the same length as the range being replaced. The string object and replacement method will resize the string automatically.
[edit ] String Search and Replace
Previously we have covered how to perform a search in a string and how to replace a subsection of a string using the rangeOfString and replaceCharactersInRange methods respectively. The fact that both of these methods use the NSRange structure enables us to combine the two methods to perform a search and replace. In the following example, we use rangeOfString to provide us with an NSRange structure for the substring to be replace and then pass this through to replaceCharactersInRange to perform the replacement:
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"]; [string1 replaceCharactersInRange: [string1 rangeOfString: @"brown fox"] withString: @"black dog"];
When executed, string1 will contain the string "The quick black dog jumped".
[edit ] Deleting Sections of a String
Similar techniques to those described above can be used to delete a subsection of a string using the deleteCharactersInRange method. As with the preceding examples, this method accepts an NSRange structure as an argument and can be combined with the rangeOfString method to perform a search and delete:
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"]; [string1 deleteCharactersInRange: [string1 rangeOfString: @"jumped"]];
[edit ] Extracting a Subsection of a String
A subsection of a string can be extracted using the substringWithRange method. The range is specified using an NSRange structure and the extracted substring is returned in the form of an NSString object:
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"]; NSString *string2; string2 = [string1 substringWithRange: NSMakeRange (4, 5)]; NSLog (@"string2 = %@", string2);
When executed, the above code will output the substring assigned to string2 ("quick").
Alternatively, a substring may be extracted from a given index until the end of the string using the subStringFromIndex method. For example:
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"]; NSString *string2; string2 = [string1 substringFromIndex: 4];
Similarly, the subStringToIndex may be used to extract a substring from the beginning of the source string up until a specified character index into the string.
[edit ] Inserting Text into a String
The insertString method inserts a substring into a string object and takes as arguments the NSString object from which the new string is to inserted and the index location into the target string where the insertion is to be performed:
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"]; [string1 insertString: @"agile, " atIndex: 4];
[edit ] Appending Text to the End of a String
Text can be appended to the end of an existing string object using the appendString method. This method directly modifies the string object on which the method is called and as such is only available for mutable string objects.
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"]; [string1 appendString: @" over the lazy dog"]; NSLog (@"string1 = %@", string1);
[edit ] Comparing Strings
String objects cannot be compared using the equality (==) operator. The reason for this is that any attempt to perform a comparison this way will simply compare whether the two string objects are located at the same memory location. Let's take a look at this via an example:
NSString *string1 = @"My String"; NSString *string2 = @"My String"; if (string1 == string2) NSLog (@"Strings match"); else NSLog (@"Strings do not match");
In the above code excerpt, string1 and string2 are pointers to two different string objects both of which contain the same character strings. If we compare them using the equality operator, however, we will get a "Strings do not match" result. This is because the if (string1 == string2) test is asking whether the pointers point to the same memory location. Since string1 and string2 point to entirely different objects the answer, obviously, is no.
We can now take this a step further and change the code so that both string1 and string2 point to the same string object:
NSString *string1 = @"My String"; NSString *string2; string2 = string1; if (string1 == string2) NSLog (@"Strings match"); else NSLog (@"Strings do not match");
Now when we run the code, we get a "Strings match" result because both variables are pointing to the same object in memory.
To truly compare the actual strings contained within two string objects we must use the isEqualToString method:
NSString *string1 = @"My String"; NSString *string2 = @"My String 2"; if ([string1 isEqualToString: string2]) NSLog (@"Strings match"); else NSLog (@"Strings do not match");
Another option is to use the compare method (to perform a case sensitive comparison) or the caseInsenstiveCompare NSString methods. These are more advanced comparison methods that can be useful when sorting strings into order.
[edit ] Checking for String Prefixes and Suffixes
A string object can be tested to identify whether the string begins or ends with a particular sequence of characters (otherwise known as prefixes and suffixes). This is achieved using the hasPrefix and hasSuffix methods respectively, both of which return boolean values based on whether a match is found or not.
NSString *string1 = @"The quick brown fox jumped"; BOOL result; result = [string1 hasPrefix: @"The"]; if (result) NSLog (@"String begins with The"); result = [string1 hasSuffix: @"dog"]; if (result) NSLog (@"String ends with dog");
Converting to Upper or Lower Case
The Foundation NSString classes provide a variety of methods for modifying different aspects of case within a string. Note that each of these methods returns a new string object reflecting the change, leaving the original string object unchanged.
- capitalizedString
Returns a copy of the specified string with the first letter of each word capitalized and all other characters in lower case:
NSString *string1 = @"The quicK brOwn fox jumpeD"; NSString *string2; string2 = [string1 capitalizedString];
The above code will return a string object containing the string "The Quick Brown Fox Jumped" and assign it to the string2 variable. The string object referenced by string1 remains unmodified.
- lowercaseString
Returns a copy of the specified string with all characters in lower case:
NSString *string1 = @"The quicK brOwn fox jumpeD"; NSString *string2; string2 = [string1 lowercaseString];
The above code will return a string object containing the string "the quick brown fox jumped" and assign it to the string2 variable. The string object referenced by string1 remains unmodified.
- uppercaseString
Returns a copy of the specified string with all characters in upper case:
NSString *string1 = @"The quicK brOwn fox jumpeD"; NSString *string2; string2 = [string1 uppercaseString];
The above code will return a string object containing the string "THE QUICK BROWN FOX JUMPED" and assign it to the string2 variable. The string object referenced by string1 remains unmodified.
Converting Strings to Numbers
String objects can be converted to a variety of number types:
- Convert String to int
NSString *string1 = @"10"; int myInt = [string1 intValue]; NSLog (@"%i", myInt);
- Convert String to double
NSString *string1 = @"10.1092"; double myDouble = [string1 doubleValue]; NSLog (@"%f", myDouble);
- Convert String to float
NSString *string1 = @"10.1092"; float myFloat = [string1 floatValue]; NSLog (@"%f", myFloat);
- Convert String to NSInteger
NSString *string1 = @"10"; NSInteger myInteger = [string1 integerValue]; NSLog (@"%li", myInteger);
Converting a String Object to ASCII
The string contained within a string object can be extracted and converted to an ASCII C style character string using the UTF8String method. For example:
NSString *string1 = @"The quick browen fox"; const char *utfString = [string1 UTF8String]; printf ("Converted string = %s\n", utfString);
发表评论
-
property “assign” and “retain” for delegate
2012-06-25 01:11 11741 Answer active oldest vo ... -
如何从一个方法中返回来自于集合的对象
2012-06-25 00:20 1080- (ImageScrollView *)dequeue ... -
类似Tweetie那种拽下来就refresh的代码
2012-06-22 12:28 849http://github.com/enormego/EGOT ... -
difference between frame and bounds Property
2012-06-17 21:55 1304bounds The bounds rectangle, wh ... -
Apple Offical : View Programming Guide for iOS
2012-06-16 17:06 1057https://developer.apple.com/lib ... -
use UINavigationController inside a UITabBarController
2012-06-16 13:39 1589If you want to add a UINavigati ... -
关于ios中bounds与frame
2012-06-16 12:03 19801.ios中的bounds是指相对于视图自己的坐标,所以默认v ... -
Enum常量放入NSArray的方法
2010-09-07 23:14 2514ypedef enum { UIViewAnim ... -
What is Core Data?
2010-08-31 22:03 1370Path to Success The Core Data P ... -
Iphone开发常用软件
2010-07-19 16:41 882粒子特效:particleillusion -
iPhone にインストールされているフォント一覧
2010-07-19 13:21 1577タイトルの通り、iPhone にインストールされているフォン ... -
Cocoaのメモリ管理(3)
2010-07-15 14:42 745保持と解除という方法 ... -
The cocos2d Tips & Tricks
2010-07-02 14:32 1106The cocos2d Tips & Tricks i ... -
Declared Properties
2010-06-30 14:13 933Writability These attributes s ...
相关推荐
《从 C++ 到 Objective-C 快速精通》是一本专为C++程序员设计的指南,旨在帮助他们迅速掌握Objective-C这门强大的编程语言。Objective-C是苹果平台上的主要开发语言,尤其在iOS和macOS应用程序开发中占据核心地位。...
### Objective-C 入门指南基础与实践 #### 一、为什么选择 Objective-C Objective-C 作为苹果公司操作系统(macOS 和 iOS)的核心开发语言之一,具有以下显著优势: 1. **苹果生态:** Objective-C 在苹果的生态...
《Objective-C编程指南》 Objective-C,作为iPhone应用开发的核心语言,是苹果生态系统中的关键组件。这个编程语言在iOS和macOS的开发中扮演着重要角色。Objective-C是由C语言扩展而来的,增加了面向对象的特性,...
Objective-C中的字符串处理通常不使用C语言的字符数组,而是使用`NSString`类。`NSString`是一个不可变的字符串对象,支持Unicode,方便进行格式化和内存管理。创建字符串可以通过直接赋值或使用`stringWithFormat:`...
如同C语言一样,Objective-C使用标头文件(header files)和源文件(source files)来分离公开声明部分和实现细节。Objective-C文件采用特定的文件扩展名,如表一所示: | 文件扩展名 | 类型 | |------------|-----...
Objective-C是一种强大的面向对象的编程语言,特别是在Apple的iOS和macOS开发中占据主导地位。本入门指南将帮助初学者理解...Objective-C入门指南.pdf文件将提供更详细的讲解和示例,帮助你快速上手Objective-C编程。
- **Apple Developer Documentation**:官方文档提供了丰富的Objective-C编程指南和技术参考资料。 - **Stack Overflow**:对于编程中遇到的具体问题,Stack Overflow是一个非常好的求助平台。 - **GitHub**:GitHub...
4. **Foundation框架**:Objective-C的开发离不开Foundation框架,书中会详细阐述NSArray、NSDictionary、NSString等常用数据结构的使用,以及线程管理、文件操作和事件处理等系统服务。 5. **Cocoa与Cocoa Touch**...
标题 "Objective-C Cheatsheet" 指的是一个快速参考指南,它为开发者提供了一种在编写Objective-C代码时能够迅速查阅的便捷方式。这个速查表涵盖了Objective-C编程的基本元素,使得开发人员在编码过程中能够快速找到...
这本书"Objective-C Solutions"可能是一本关于Objective-C编程的实践指南,帮助初学者理解和解决在学习iOS开发过程中遇到的问题。 1. **面向对象编程基础**:Objective-C的基础是C语言,但它扩展了类、对象、消息...
### Objective-C Runtime编程指南知识点概览 #### 一、Objective-C Runtime系统介绍 Objective-C语言设计上尽可能地将决策从编译时和链接时推迟到运行时,这意味着它不仅仅依赖于编译器,还需要一个运行时系统来...
这篇"Objective-C基础教程.pdf.zip"提供了一个全面的指南,帮助初学者理解并掌握Objective-C的关键概念和语法。 首先,Objective-C是在C语言的基础上扩展的,因此,它保留了C语言的基本结构和特性。学习Objective-C...
- **链接**:[Apple Developer Documentation](https://developer.apple.com/documentation/objectivec) 这里不仅包含语言本身的详细介绍,还包括了苹果框架和技术的使用说明,非常适合初学者和进阶开发者。 ##...
本资源"Learn Objective-C(zh)(v2).pdf"显然是一个中文版的Objective-C学习指南,旨在帮助初学者掌握这一关键技能。 1. **Objective-C基础**:Objective-C的基础始于C语言的基本语法,包括变量、数据类型、控制流...
本文基于Daniel的Objective-C编码风格指南,结合Apple、Google及Three20的编码规范,旨在提供一套详细的Objective-C编码标准,以提升代码的可读性和维护性。 #### 二、代码格式化 1. **指针“*”号的位置**:遵循C...
### 使用Swift与Cocoa及Objective-C 在苹果的开发环境中,Swift、Cocoa以及Objective-C是三个非常重要的组成部分。本文档旨在深入探讨如何在实际项目中有效地将这三种技术结合起来,以便开发者能够更好地利用这些...