简体   繁体   中英

Retain count after creating 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 Example [1580:207] retain count == 2147483647

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

Thanks,

Do not use -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. 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.

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.

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

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

Your value is 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.

It is static string, then object can not be dealloc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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