Detailed explanation of usage of NSMutableString in Object-C

NSMutableString inherits NSString and extends NSString so that the generated string object can be modified.

Creation of NSMutableString:

NSMutableString *string = [NSMutableString string];

Cannot be created with:

NSMutableString *string = @"cannot create a new obj";

Because the pointer type on the left is a variable string type, and the right side is an NSString type. An error occurs when the object string calls a method of type NSMutableString.

The NSMutableString type has the following methods:

//在原来字符串中“loc”位置中插入一段字符串“aString”。
- (void)insertString:(NSString *)aString atIndex:(NSUInteger)loc;

//删除原来字符串中的一段字符。
- (void)deleteCharactersInRange:(NSRange)range;

//在后面拼接一段字符串。
- (void)appendString:(NSString *)aString;

//在后面拼接一段根据格式定义的字符串。
- (void)appendFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);

//原来字符串全部修改为其它字符串
- (void)setString:(NSString *)aString;

Usage scenarios of NSMutableString and NSString:

1. When there are a large number of splicing and modifying strings in the loop body more than 5 times, try to avoid creating NSString objects, because if the string content is different each time it is created, new memory space will be opened up, and too many loops will cause low efficiency. When using an NSMutableString object, it is only created once and does not repeatedly open up memory space. Therefore, it is more efficient in loops with many times.

2. Ordinary strings usually use NSString objects, because NSString will not be newly created in the memory with the same content, but will point the pointer to the existing string space with the same content. Higher efficiency.

Guess you like

Origin blog.csdn.net/JustinZYP/article/details/124205041