How to print out an object's retainCount?

Discussion in 'Mac Programming' started by CaptSaltyJack, Jul 15, 2008.

  1. CaptSaltyJack macrumors 6502

    Joined:
    Jun 28, 2007
    #1
    I'm just learning Obj-C/Cocoa, and am spending as much time as I can on the section on retain/release, so I fully understand it.

    I'm trying to print out an object's retainCount, but it keeps printing as:

    2008-07-16 00:59:42.872 Learn[7227:10b] retainCount = 2147483647

    What am I doing wrong? Below is the relevant part of the code.

    Code:
    - (IBAction) doit: (id)sender
    {
    	NSString *hi = @"Here's a test";
    	NSLog(@"retainCount = %d", [hi retainCount]);
    }
    
     
  2. kpua macrumors 6502

    Joined:
    Jul 25, 2006
    #2
    Everything is exactly correct, except your approach at learning reference counting.

    The retain count of NSConstantString objects (made with the @"" syntax) is always the maximum integer value, because they cannot be deallocated.

    Cocoa does interesting things with the retain counts of its classes very often—they should not be relied upon. You will only get confused even more. Just focus on the essential ownership principles. They will be the most useful.
     
  3. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #3
    This has come up a few times here, and the real lesson is that you should not depend on retainCount for much of anything. Inspecting the runtime in your code is at best an exercise in curiosity, but will rarely prove to be useful. There are other cases like this, such as NSNumbers created with integer values from 0 to, I believe, 12. These are always kept handy by the runtime, and they have a retain count of your system's MAX_INT. In this case it's the largest positive value for a 32-bit int.

    Essentially the runtime authors have decided that some things should never be freed because they are so commonly used, or are literals setup in your program whose value must always be available.

    -Lee
     

Share This Page