开发者

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开发者_JAVA技巧]);

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


constants and literals have retain count = INT_MAX, they can't be released as they are allocated separately not on heap with other objects (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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜