22 - String NSMutableString

1. String constancy.
Once a string object is created, the content of the string object cannot be changed. When we modify the string, we actually recreate a string object.
Code case:
NSLog(@"-------------------");
NSString *str = @""; //@""
for(int i = 0; i < 50000; i++)
{
str = [NSString stringWithFormat:@"%@%d",str,i];
}
NSLog(@"-------------------");
It will take a long time. A new string object will be created each time the loop. 50000,
Because of the constancy of strings.
2. How to make such a large batch of string splicing can be faster 1 point.
1). The reason for the slowness: Because of the constancy of the string, every time the string is modified, an object is recreated,
2). Hope: Is there an object that is used to store strings, and the string data stored in this object can be changed.
3. NSMutableString
1). Is a class in the Foundation framework. Inherited from NSString.
So, NSMutableString objects are used to store string data.
2). NSMubaleString is extended on the basis of the parent class NSString.
String data stored in NSSMutableString objects can be changed. Mutable.
You can directly change the string data stored in the NSMutableStirng object without creating a new object.
4. Usage of NSMutableString
1). Since it is a class, if you want to use it, you have to create an object.
NSMutableString *str = [NSMutableString string];
2). Append a string to a mutable string object.
- (void)appendString:(NSString *)aString; 直接追加内容.
- (void)appendFormat:(NSString *)format, ... 以拼接的方式往可变字符串对象中追加内容.
3). 创建NSMutableString对象的时候,记住下面这样的初始化方式是不行的.
NSMutableString *str = @"jack";
@"jack" 是1个NSString对象,是1个父类对象.
而str指针是1个NSMutableString类型的 是1个子类类型的.
如果通过子类指针去调用子类独有的成员 就会运行错误.
4). NSMutableString从NSString继承.
在使用NSString的地方完全可以使用NSMutableString
5. 使用NSMutableString来做大批量的字符串拼接.
NSLog(@"~~~~~~~~~~~~");
NSMutableString *str = [NSMutableString string];
for(int i = 0; i < 100000; i++)
{
[str appendFormat:@"%d",i];
}
NSLog(@"~~~~~~~~~~~~");
这个时候 "biu"的一下就结束了. 为什么这么快>? 因为NSMutableString只有1个.每次修改的时候 直接修改的是这个对象中的数据.
6. 使用建议
1). 我们平时使用的时候,还是使用NSString. 因为效率高.
NSString *str1 = @"jack";
NSString *str2 = @"jack";
2). NSMutbaleString: 只在做大批量的字符串拼接的时候才使用.
大量拼接的时候,就不要去使用NSString 因为效率低下.\
10次以上.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325899918&siteId=291194637