我有一个疑问,当我创建一个NSMutableString对象时,它指向两个单独的内存位置,但是当我使用NSString时,它指向了相同的位置。谁能解释一下这背后的逻辑。

 NSMutableString *myString1 = [NSMutableString new];
 NSMutableString *myString2 = [NSMutableString new];
 NSLog(@"%p",myString1);0x00007fe572416da0
 NSLog(@"%p",myString2);0x00007fe5724114a0

NSString *myString3 = [NSString new];
NSString *myString4 = [NSString new];
NSLog(@"%p",myString3);0x10622e470
NSLog(@"%p",myString4);0x10622e470

最佳答案

我将根据使用的内存进行解释。下面我详细介绍了在非ARC情况下这些变量的保留计数

NSMutableString *myString1 = [NSMutableString new];

NSLog(@"String Retain Count: %lu", (unsigned long)[myString1 retainCount]); //String Retain Count: 1

NSString *myString3 = [NSString new];

NSLog(@"String Retain Count: %lu", (unsigned long)[myString3 retainCount]); //String Retain Count: 18446744073709551615

因此,在第二种情况下,它被视为常量字符串。它将您的字符串视为NSConstantString。

关于ios - NSString和NSMutableString的内存分配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37045499/

10-11 01:56