NSString属性何时用strong何时用copy?
程序员文章站
2023-12-21 09:29:34
前言
我们在声明一个nsstring属性时,对于其内存相关特性,通常有两种选择(基于arc环境):strong与copy。那这两者有什么区别呢?什么时候该用strong,...
前言
我们在声明一个nsstring属性时,对于其内存相关特性,通常有两种选择(基于arc环境):strong与copy。那这两者有什么区别呢?什么时候该用strong,什么时候该用copy呢?让我们先来看个例子。
代码验证
@property (nonatomic, strong) nsstring *mystrongstring; @property (nonatomic, copy) nsstring *mycopystring; - (void)stringtest { nsmutablestring *mutablestr = [nsmutablestring stringwithformat:@"https://"]; self.mystrongstring = mutablestr; self.mycopystring = mutablestr; nslog(@"mutablestr:%p,%p", mutablestr,&mutablestr); nslog(@"strongstring:%p,%p", _mystrongstring, &_mystrongstring); nslog(@"copystring:%p,%p", _mycopystring, &_mycopystring); //---------------分割线--------------------- [mutablestr appendstring:@"devthinking.com"]; nslog(@"strongstring:%p,%p", _mystrongstring, &_mystrongstring); nslog(@"copystring:%p,%p", _mycopystring, &_mycopystring); }
打印日志如下:
2016-11-09 14:14:18.532 democollectoc[92929:1731791] mutablestr:0x60800026fe00,0x7fff549c9be8 2016-11-09 14:14:18.532 democollectoc[92929:1731791] strongstring:0x60800026fe00,0x7ff095402308 2016-11-09 14:14:18.533 democollectoc[92929:1731791] copystring:0x6080004234a0,0x7ff095402310 2016-11-09 14:14:18.533 democollectoc[92929:1731791] strongstring:0x60800026fe00,0x7ff095402308 2016-11-09 14:14:21.039 democollectoc[92929:1731791] copystring:0x6080004234a0,0x7ff095402310
结论
1.mystrongstring跟mutablestr的指向地址始终一样,都为0x60800026fe00,mycopystring跟mutablestr指向的地址不同,即为深copy,新开辟了一份内存;
2.赋值时,当原始字符串是mutable string时,存在此差异,当mutablestr变化时,mystrongstring会随着改变,而mycopystring则不会。通常我们不想让其随着改变,故用copy属性较多;如果我们想其随着改变,则用strong。
3. 如果原始赋值字符串为string时,则用copy和strong属性是一样的。
变量存储地址
- &取地址符,取出来的是变量的存储地址,如mystrongstring mycopystring是存在堆里的,地址以0x7ff09开头,mutablestr为临时变量,是存在栈里的,以0x7fff5开头。
- 直接p打印出来的地址,则是存储内容实际存在的地址,其实里面存储的还是地址,详细的请看下一节,但是我们可以用这个地址区间来判断存储的区域。
附:x/3gx查看对象内存
查看基本数据类型的内存时,可直接查看,16进制转化一下就可以,查看对象时,则不可以,这跟string的结构体是相关的:
以nsstring为例
nsstring *str = @"a";
先打印出地址:
(lldb) p str (__nscfconstantstring *) $0 = 0x0000000109b3aa30 @"a"
再用x/3gx命令查看内存:
(lldb) x/3gx 0x0000000109b3aa30 0x109b3aa30: 0x000000010bf3e348 0x00000000000007c8 0x109b3aa40: 0x0000000109b276db
再查看0x0000000109b276db中的地址即为字母a的ascii码实际存在地址:
(lldb) p (char*)0x0000000109b276db (char *) $2 = 0x0000000109b276db "a"
可以直接在变量上右键上打开view memory of “*str”, 这就打开memory查看,在address里面输上0x0000000109b276db,即可查看每个字节的内容。
总结
以上就是这篇文章的全部内容,希望本文的内容对各位ios开发者们能有所帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。
推荐阅读
-
NSString属性何时用strong何时用copy?
-
iOS 开发 NSString(NSDictory,NSArray)为什么用copy修饰,而不是用strong修饰
-
NSString什么时候用copy,什么时候用strong
-
iOS @property中的NSString, NSArray, NSDictionary属性为什么大多时候用copy而不用strong的原因
-
iOS 开发 NSString(NSDictory,NSArray)为什么用copy修饰,而不是用strong修饰
-
NSString什么时候用copy,什么时候用strong
-
iOS @property中的NSString, NSArray, NSDictionary属性为什么大多时候用copy而不用strong的原因
-
iOS开发 -- 属性用copy、strong修饰的区别