探讨NSString在哪个内存区
Posted 拳不离手
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了探讨NSString在哪个内存区相关的知识,希望对你有一定的参考价值。
1 NSString *str = [[NSString alloc] initWithFormat:@"不可变"];//在堆区 2 NSLog(@"p = %p; str = %ld",str, [str retainCount]);// 3 4 self.retainStr = str;// 浅拷贝。引用计数 +1 5 NSLog(@"p = %p; self.retainStr = %ld",self.retainStr,[self.retainStr retainCount]);// 6 self.copyStr = str;// 浅拷贝。引用计数再 +1 7 NSLog(@"p = %p; self.copyStr = %ld",self.copyStr,[self.copyStr retainCount]); 8 9 self.retainMStr = [str mutableCopy];// 深拷贝。mutableCopy,引用计数 +1;retain,再 +1。 10 NSLog(@"p = %p; self.retainMStr = %ld",self.retainMStr,[self.retainMStr retainCount]); 11 self.copyMStr = [str mutableCopy];// 深拷贝。mutableCopy,引用计数 +1;copy,不增加。 12 NSLog(@"p = %p; self.copyMStr = %ld",self.copyMStr,[self.copyMStr retainCount]); 13 14 15 16 NSLog(@"-------------------------------"); 17 18 NSMutableString *mutableStr = [[NSMutableString alloc] initWithFormat:@"可变字符串"];//在堆区 19 NSLog(@"p = %p; mutableStr = %ld",mutableStr, [mutableStr retainCount]);// 20 21 self.retainStr = mutableStr;// 单纯地持有。所以,与mutableStr同地址。引用计数 +1 22 NSLog(@"p = %p; self.retainStr = %ld",self.retainStr, [self.retainStr retainCount]);// 23 self.copyStr = mutableStr;// 深拷贝。与mutableStr不同地址,引用计数 =1 24 NSLog(@"p = %p; self.copyStr = %ld",self.copyStr, [self.copyStr retainCount]); 25 26 self.retainMStr = mutableStr;// 单纯地持有。所以,与mutableStr同地址。引用计数再 +1 27 NSLog(@"p = %p; self.retainMStr = %ld",self.retainMStr, [self.retainMStr retainCount]); 28 self.copyMStr = mutableStr;// 深拷贝。与mutableStr和self.copyStr的地址皆不同,引用计数 =1 29 NSLog(@"p = %p; self.copyMStr = %ld",self.copyMStr, [self.copyMStr retainCount]);
1 2016-06-16 16:15:32.015 OCLession9[10611:174179] p = 0x100600960; str = 1 2 2016-06-16 16:15:32.015 OCLession9[10611:174179] p = 0x100600960; self.retainStr = 2 3 2016-06-16 16:15:32.016 OCLession9[10611:174179] p = 0x100600960; self.copyStr = 3 4 2016-06-16 16:15:32.016 OCLession9[10611:174179] p = 0x100300350; self.retainMStr = 2 5 2016-06-16 16:15:32.016 OCLession9[10611:174179] p = 0x1003003e0; self.copyMStr = 1 6 2016-06-16 16:15:32.016 OCLession9[10611:174179] ------------------------------- 7 2016-06-16 16:15:32.016 OCLession9[10611:174179] p = 0x1003004b0; mutableStr = 1 8 2016-06-16 16:15:32.016 OCLession9[10611:174179] p = 0x1003004b0; self.retainStr = 2 9 2016-06-16 16:15:32.017 OCLession9[10611:174179] p = 0x100203ae0; self.copyStr = 1 10 2016-06-16 16:15:32.017 OCLession9[10611:174179] p = 0x1003004b0; self.retainMStr = 3 11 2016-06-16 16:15:32.017 OCLession9[10611:174179] p = 0x100203b10; self.copyMStr = 1
堆区:NSString *str = [[NSString alloc] initWithFormat:@"不可变"];//其中有汉字,是unicode,所以在堆区
常量区:NSString *str = [[NSString alloc] initWithFormat:@"123abc"];//纯在Ascll码,例如字母与数字的混合,编译器会在编译期用“悬垂指针”对其进行优化。可理解为在常量区。反正引用计数对此失效。
常量区:NSString *str = @"我来了";//[[NSString alloc] initWithString:@"我来了"];//两种方式都一样。都在常量区
以上是关于探讨NSString在哪个内存区的主要内容,如果未能解决你的问题,请参考以下文章