0

I am trying to print out the retain count of an object in the terminal using NSLog. Here is my code:

NSNumber *myInt=[[NSNumber alloc] initWithInteger: 100];
NSLog(@"myInt retain count=%d",[myInt retainCount]);

The result should be 1 but what I have got at the terminal is -1. I tried to use %u instead of %d and ended up getting 4294967295 as result. Does anyone know why this happens?

vcsjones
  • 138,677
  • 31
  • 291
  • 286
God_of_Thunder
  • 753
  • 3
  • 20
  • 46
  • 1
    `retainCount` is useless. Don't call it. What you are seeing is an implementation detail; the `NSNumber` returned is probably a *tagged pointer* and, thus, there is no allocation and nothing to retain. – bbum Jul 16 '12 at 16:17
  • So all the books talking about returnCount functionality are simply bullshitting then? – God_of_Thunder Jul 17 '12 at 12:29
  • 1
    They may be misguided rather than bullshitting, but they're inaccurate. –  Jul 17 '12 at 12:37
  • 1
    Yup; any book that discusses retainCount as if it were useful is suspect. An object's retainCount only makes sense when there is no threading, no autorelease, no passes through system APIs, and you aren't subclassing a framework class, among other things. http://whentouseretaincount.com/ – bbum Jul 17 '12 at 15:24

1 Answers1

3

Before @bbum gets here I get to say this:

Don't rely on -retainCount in your code

It doesn't give you answers you expect. It turns out that the answer -1 is correct here, the fact that you don't think it's correct is because the framework is doing something you don't know about behind your back. Use automatic reference counting (ARC), or if you must use manual retain/release just follow the memory management guidelines without using the -retainCount method.