Behavior of __block modifier in objc

48 Views Asked by At

We know __block makes blocks not retain the objects, but why this happens:

#import "ViewController.h"

@interface TestClass : NSObject

@end

@implementation TestClass

- (void)dealloc {
    NSLog(@"test class deinit..");
}

@end

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __block TestClass *testClass = [[TestClass alloc] init];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
        NSLog(@"testClass: %@", testClass);
    });
}

@end

Output:

testClass: <TestClass: 0x6000000045e0>
test class deinit..

If the block doesn't retain testClass, shouldn't it be nil when we print it?

0

There are 0 best solutions below