创建NSString后保留计数 [英] Retain count after creating NSString

查看:38
本文介绍了创建NSString后保留计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过以下方法创建一个NSString类型的对象

I am creating a object which is type of NSString by the below method

NSString *str = [[NSString alloc] initWithString:@"aaaaaaaaaaaaaaa"];
    NSLog(@"retain count == %d",[str retainCount]);

之后,我只打印保留计数值

after that i just printing the retain count value which is

2010-10-29 17:04:03.939示例[1580:207]保留计数== 2147483647

2010-10-29 17:04:03.939 Example [1580:207] retain count == 2147483647

任何人都可以回答这个问题,为什么这里的日志中会打印出这样的垃圾值

can any one answer this why here log is printing such garbage value

谢谢

推荐答案

您正在根据字符串文字创建不可变的NSString对象.字符串文字是在编译时创建的,并且在程序的整个运行时都处于活动状态-因此无法将其释放,并且保留/释放对其不起作用.为了进行优化(因为您的NSString始终是不可变的), -initWithString:方法可以只返回传递给它的字符串,以便将字符串文字地址分配给您的str变量.

You're creating an immutable NSString object from a string literal. String literals are created at compile time and live for the whole run-time of your program - so it cannot be deallocated and retain/release has no effect on it. For optimization (as your NSString is immutable anyway) -initWithString: method can just return the string passed to it and so that string literal address becomes assigned to your str variable.

如果您将初始化代码更改为 -initWithFormat:,那么我想您将获得预期的保留计数值

If you change your initialization code to -initWithFormat: then I suppose you'll get expected retain count value

这篇关于创建NSString后保留计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆