0

I‘m testing block retainCount for object var.

__block Person *person = [[Person alloc] init];
    NSLog(@"Block前person的引用计数%ld, 地址%@,指针:%p", CFGetRetainCount((__bridge CFTypeRef)person), person, &person);
    void (^myBlock)(void) = ^{
        person.name = @"Nature";
        NSLog(@"Block中person的引用计数%ld, 地址是%@, 指针: %p", CFGetRetainCount((__bridge CFTypeRef)person), person, &person);
    };
    myBlock();
    NSLog(@"Block后person的引用计数%ld", CFGetRetainCount((__bridge CFTypeRef)person));

The retainCount is 1. When remove __block, the output is 3! Can anyone explain why is 1 with __block, and is 3 without __block. Thank you!

user6299706
  • 101
  • 8
  • Variations of this question have been asked and answered many times. I'd suggest you search Stack Overflow for `CFGetRetainCount` and you'll get lots of hits. The short answer is that you simply shouldn't use retain counts anymore. E.g. https://stackoverflow.com/q/4636146/1271826. If you really care, look at the dissembly for both scenarios and you can see what's really going on, but it's not a terribly fruitful or useful exercise. – Rob Dec 07 '21 at 04:26

0 Answers0