-3

I am doing some simple testing of retaincount, all I get is -1.

For example,

 NSString *s1 = [[NSString alloc] init];
    NSLog(@"s1 Retain Count = %d",[s1 retainCount]);

    NSString *s2 = [NSString string];
    NSLog(@"s2 Retain Count = %d",[s2 retainCount]);

I am wondering if there is anyway to get the internal retaincount?

Adam Lee
  • 21,598
  • 43
  • 138
  • 208

2 Answers2

4
NSLog(@"s1 Retain Count = %lu",(unsigned long)[s1 retainCount]);

If you'd used the correct format specifier — a warning should tell you to do so — you'd see

retaincoundt[11169:438727] s1 Retain Count = 18446744073709551615
retaincoundt[11169:438727] s2 Retain Count = 18446744073709551615

or 264 - 1 -> NSUIntegerMax on 64 bit systems. You are looking on a constant object. The compiler had identified room for optimisation by pointing to the same ever present constant immutable object.

Things like these may happen or not at any time. You can't and shouldn't rely on retainCount.

vikingosegundo
  • 51,126
  • 14
  • 131
  • 172
0

Take a look at the Apple Doc's..

Declaration OBJECTIVE-C - (NSUInteger)retainCount Return Value The receiver’s reference count.

Special Considerations This method is of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.

To understand the fundamental rules of memory management that you must abide by, read Memory Management Policy. To diagnose memory management problems, use a suitable tool:

The Clang Static analyzer can typically find memory management problems even before you run your program.

The Object Alloc instrument in the Instruments application (see Instruments User Guide) can track object allocation and destruction.

Priyatham51
  • 1,804
  • 1
  • 16
  • 23