4

Possible Duplicate:
NSString retain Count

Is it possible that any object has its retain count in negative value ?

I have this code

NSString *str = [[NSString alloc] initWithString:@"Hello World"];
NSLog(@"String Retain Count: %i", [str retainCount]);

this will return the retain count -1.

Why this happened ?

also I have done like this

NSString *str = [[NSString alloc] init]

still its return negative value in retain count.

How this is happening ?

Please help to understand this thing!!!!!

Community
  • 1
  • 1
Muhammad Rizwan
  • 3,470
  • 1
  • 27
  • 35
  • RetainCount is pretty much useless, as detailed here: http://stackoverflow.com/questions/4636146/when-to-use-retaincount – T. Benjamin Larsen Jan 30 '13 at 10:07
  • @kuba this is not a duplicate of that question so Please read what is my question. – Muhammad Rizwan Jan 30 '13 at 10:09
  • 2
    @Rizzu: It *is a duplicate*. The returned retain count is `2147483647 ` and you got the output `-1` only because you printed the value with the `%i` format for signed integers. – Martin R Jan 30 '13 at 10:17
  • Ok then what about "NSString *str = [[NSString alloc] init] " ? – Muhammad Rizwan Jan 30 '13 at 10:19
  • @Rizzu: `[[NSString alloc] init]` returns a constant empty string. - The retain count is a `NSUInteger` so it *cannot be negative*. – Martin R Jan 30 '13 at 10:25
  • @Rizzu It's just that you invoke UB by printing an unsigned integer using `%i` instead of `%llu`. –  Jan 30 '13 at 10:45

1 Answers1

6

retainCount doesn't return the reference count of an object. - it returns unrelated nonsense.

(For performance reasons, immutable constant strings, when copied, return self. If you compare the pointer to @"" and [[NSString alloc] initWithString:@""], they will be equal.)

  • Just a note: `[[NSString alloc] initWithString:@""]` returns the same pointer as `@""`, but `[[NSString alloc] init]` returns a different (unique) pointer. – Martin R Jan 30 '13 at 10:50
  • @MartinR Thanks, updated. (How suboptimal Apple's code is! :P) –  Jan 30 '13 at 10:55