简体   繁体   English

创建NSString后保留计数

[英]Retain count after creating NSString

I am creating a object which is type of NSString by the below method 我正在通过以下方法创建一个NSString类型的对象

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 Example [1580:207] retain count == 2147483647 2010-10-29 17:04:03.939示例[1580:207]保留计数== 2147483647

can any one answer this why here log is printing such garbage value 可以任何人回答这个为什么这里的日志打印这样的垃圾值

Thanks, 谢谢,

Do not use -retainCount. 不要使用-retainCount。

The absolute retain count of an object is meaningless. 对象的绝对保留计数是没有意义的。

You should call release exactly same number of times that you caused the object to be retained. 您应该将release的次数与导致保留对象的次数完全相同。 No less (unless you like leaks) and, certainly, no more (unless you like crashes). 不会少(除非你喜欢泄漏),当然,没有更多(除非你喜欢崩溃)。

See the Memory Management Guidelines for full details. 有关完整详细信息,请参阅内存管理指南


In this specific case, you caused one retain with the call to alloc and, thus, you need to call release (or autorelease ) once somewhere, anywhere, in your code. 在这种特定情况下,您通过调用alloc导致一个retain ,因此,您需要在代码中的某个地方,任何地方调用release (或autorelease )。

You're creating an immutable NSString object from a string literal. 您正在从字符串文字创建不可变的NSString对象。 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. 为了优化(因为你的NSString无论如何都是不可变的) -initWithString:方法只能返回传递给它的字符串,以便字符串文字地址分配给你的str变量。

If you change your initialization code to -initWithFormat: then I suppose you'll get expected retain count value 如果您将初始化代码更改为-initWithFormat:那么我认为您将获得预期的保留计数值

常量和文字有保留count = INT_MAX,它们不能被释放,因为它们是单独分配的,不在堆上与其他对象分配(afaik)

Your value is UINT_MAX=0x7FFFFFFF 您的值为UINT_MAX = 0x7FFFFFFF

You might override this method in a class to implement your own reference-counting scheme. 您可以在类中重写此方法以实现您自己的引用计数方案。 For objects that never get released (that is, their release method does nothing), this method should return UINT_MAX, as defined in limits.h. 对于永不释放的对象(即,它们的释放方法不执行任何操作),此方法应返回UINT_MAX,如limits.h中所定义。

It is static string, then object can not be dealloc. 它是静态字符串,然后对象不能被dealloc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM