NSMutableString 繼承自 NSString,擁有所有不可變字符串方法,另提供原地修改方法。
NSMutableString *str = [NSMutableString stringWithString:@"abc"];
[str insertString:@"xyz" atIndex:2]; // 在索引 2 處插入
NSLog(@"%@", str); // 輸出: abxyzc
[str replaceCharactersInRange:NSMakeRange(0, 3) withString:@"123"];
NSLog(@"%@", str); // 輸出: 123yzc (原 0-2 替換為 123)
[str deleteCharactersInRange:NSMakeRange(0, 3)];
NSLog(@"%@", str); // 輸出: yzc (刪除前 3 字符)
NSRange range = NSMakeRange(location, length);
// location: 起始索引 (0-based)
// length: 字符數
NSMutableString *s = [NSMutableString stringWithString:@"Hello World"];
NSLog(@"原始: %@", s); // Hello World
[s insertString:@" Beautiful" atIndex:5];
NSLog(@"插入後: %@", s); // Hello Beautiful World
[s replaceCharactersInRange:NSMakeRange(0, 5) withString:@"Hi"];
NSLog(@"替換後: %@", s); // Hi Beautiful World
[s deleteCharactersInRange:NSMakeRange(2, 10)];
NSLog(@"刪除後: %@", s); // Hi World
| 場景 | 推薦類型 | 理由 |
|---|---|---|
| 頻繁拼接、修改 | NSMutableString | 原地修改,避免重複分配拷貝 |
| 多線程共享、只讀 | NSString | 不可變天然線程安全 |
| 字典鍵、集合元素 | NSString | 不可變保證哈希值穩定 |
| 構建過程中修改、最終定型 | NSMutableString → copy | 構建用可變,定型用 copy 產生不可變快照 |