NSString属性何时用strong何时用copy?

2025-05-29 0 24

前言

我们在声明一个nsstring属性时,对于其内存相关特性,通常有两种选择(基于arc环境):strong与copy。那这两者有什么区别呢?什么时候该用strong,什么时候该用copy呢?让我们先来看个例子。

代码验证

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
@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);

}

打印日志如下:

?

1

2

3

4

5
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属性是一样的。

变量存储地址

  1. &取地址符,取出来的是变量的存储地址,如mystrongstring mycopystring是存在堆里的,地址以0x7ff09开头,mutablestr为临时变量,是存在栈里的,以0x7fff5开头。
  2. 直接p打印出来的地址,则是存储内容实际存在的地址,其实里面存储的还是地址,详细的请看下一节,但是我们可以用这个地址区间来判断存储的区域。

附:x/3gx查看对象内存

查看基本数据类型的内存时,可直接查看,16进制转化一下就可以,查看对象时,则不可以,这跟string的结构体是相关的:

NSString属性何时用strong何时用copy?

以nsstring为例

?

1
nsstring *str = @"a";

先打印出地址:

?

1

2
(lldb) p str

(__nscfconstantstring *) $0 = 0x0000000109b3aa30 @"a"

再用x/3gx命令查看内存:

?

1

2

3
(lldb) x/3gx 0x0000000109b3aa30

0x109b3aa30: 0x000000010bf3e348 0x00000000000007c8

0x109b3aa40: 0x0000000109b276db

再查看0x0000000109b276db中的地址即为字母a的ascii码实际存在地址:

?

1

2
(lldb) p (char*)0x0000000109b276db

(char *) $2 = 0x0000000109b276db "a"

可以直接在变量上右键上打开view memory of “*str”, 这就打开memory查看,在address里面输上0x0000000109b276db,即可查看每个字节的内容。

NSString属性何时用strong何时用copy?

总结

以上就是这篇文章的全部内容,希望本文的内容对各位ios开发者们能有所帮助,如果有疑问大家可以留言交流,谢谢大家对快网idc的支持。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 NSString属性何时用strong何时用copy? https://www.kuaiidc.com/91966.html

相关文章

发表评论
暂无评论