NSColor objects have negative retainCount (-1)

  • I was trying to track down a bug, and so got overly defensive, by adding
    Asserts to my dealloc code.  And when I attempted to verify that a
    NSColor object was valid before releasing it, I keep getting complaints
    about it having a retain count of -1.  After hours of verifying every
    retain/release of colors, I could only conclude that it was starting out
    at -1.

    So I created a simple test case:

    int main (int argc, const char * argv[])
    {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    {
      NSColor* rColor = [NSColor redColor];
      NSColor* bColor = [NSColor blueColor];
      NSColor* gColor = [NSColor colorWithDeviceRed:0.0 green:1.0
    blue:0.0 alpha:1.0];

      int count = [rColor retainCount];

      NSLog(@"Red's retain count = %d", count);

      count = [bColor retainCount];
      NSLog(@"Blue's retain count = %d", count);

      count = [gColor retainCount];
      NSLog(@"Green's retain count = %d", count);
    }
    [pool release];
    return 0;
    }

    The red and blue colors have retain counts of -1 immediately after
    calling the factory methods.  But the green color does have a retain
    count of 1, as expected.

    Is there some reason the standard colors are being returned with a
    negative retain count?

    On a related note.  Sometimes in the debugger, my color member variable
    for a class, will not appear as a pointer.  I don't know if memory is
    getting corrupted due to the -1 issue, or if it's just a problem with
    the debugger.  But it's annoying.

    TIA,
    Brant
  • > I was trying to track down a bug, and so got overly defensive, by
    > adding Asserts to my dealloc code.  And when I attempted to verify that
    > a NSColor object was valid before releasing it, I keep getting
    > complaints about it having a retain count of -1.  After hours of
    > verifying every retain/release of colors, I could only conclude that it
    > was starting out at -1.
    > ...
    > NSColor* rColor = [NSColor redColor];
    > NSColor* bColor = [NSColor blueColor];
    > NSColor* gColor = [NSColor colorWithDeviceRed:0.0 green:1.0
    > blue:0.0 alpha:1.0];

    Actually that is a retain count of UINT_MAX, as retain counts are
    unsigned. They are pegged at max.

    Also, the reason why gColor has a retain count of 1 while the other two
    are UINT_MAX is bacause the first two are cached colors (an
    implementation optimization).

    Ali
previous month april 2001 next month
MTWTFSS
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30            
Go to today