0

I have following code:

int main(int argc, char *argv[])
{

    void *pointer = NULL;

    @autoreleasepool {

        NSMutableArray *arr = [[NSMutableArray alloc] init];

        pointer = (__bridge_retained void *)arr;

        NSLog(@"retain count: %d\n", (NSInteger)CFGetRetainCount((__bridge CFMutableArrayRef)arr)); // 2
    }

    // Why this line retains an object?
    NSMutableArray __weak *cocoaArr = (__bridge NSMutableArray *)pointer;

    NSLog(@"retain count: %d", (NSInteger) CFGetRetainCount((__bridge CFMutableArrayRef)cocoaArr));
    NSLog(@"retain count: %d", (NSInteger)CFGetRetainCount((__bridge CFMutableArrayRef)((__bridge NSMutableArray *)pointer))); // 2

    return 0;
}

Output:

2013-05-11 11:44:12.488 __iOS_SimpleConsoleApplication[16667:c07] retain count: 2
2013-05-11 11:44:12.491 __iOS_SimpleConsoleApplication[16667:c07] retain count: 2
2013-05-11 11:44:12.492 __iOS_SimpleConsoleApplication[16667:c07] retain count: 2

Interesting thing... if I use this code snippet:

    NSMutableArray __weak *cocoaArr = (__bridge NSMutableArray *)pointer; // Why this line retains an object?

//    NSLog(@"retain count: %d", (NSInteger) CFGetRetainCount((__bridge CFMutableArrayRef)cocoaArr));
    NSLog(@"retain count: %d", (NSInteger)CFGetRetainCount((__bridge CFMutableArrayRef)((__bridge NSMutableArray *)pointer))); // 2

Output is:

2013-05-11 11:53:52.416 __iOS_SimpleConsoleApplication[16878:c07] retain count: 2
2013-05-11 11:53:52.421 __iOS_SimpleConsoleApplication[16878:c07] retain count: 1

If I use this:

    NSMutableArray __weak *cocoaArr = (__bridge NSMutableArray *)pointer; // Why this line retains an object?

    NSLog(@"retain count: %d", (NSInteger) CFGetRetainCount((__bridge CFMutableArrayRef)cocoaArr));
//    NSLog(@"retain count: %d", (NSInteger)CFGetRetainCount((__bridge CFMutableArrayRef)((__bridge NSMutableArray *)pointer))); // 2

Output is:

2013-05-11 11:54:23.742 __iOS_SimpleConsoleApplication[16904:c07] retain count: 2
2013-05-11 11:54:23.745 __iOS_SimpleConsoleApplication[16904:c07] retain count: 2
AndrewShmig
  • 4,843
  • 6
  • 39
  • 68
  • 2
    Don't ***ever*** rely on `-retainCount` for anything. Try getting the retain count of `@""` to see what I mean. – CodaFi May 11 '13 at 08:19
  • 1
    In your case, it is the `NSLog(... cocoaArr))` that retains+autoreleases the object. – Martin R May 11 '13 at 08:27
  • Which makes perfect sense because that's apple's way of implementing the "poor man's atomic return values" – CodaFi May 11 '13 at 08:35

0 Answers0