Why variable with __weak qualifier retains an object?

前端 未结 1 1110
醉酒成梦
醉酒成梦 2021-01-13 18:07

Here is my code:

extern void _objc_autoreleasePoolPrint();

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

    NSArray __weak *tmp = nil;

    @autoreleasepool {         


        
相关标签:
1条回答
  • 2021-01-13 18:31

    It seems that [[NSArray alloc] init] returns a "shared instance" of an empty NSArray:

    NSArray *a = [[NSArray alloc] init];
    NSArray *b = [[NSArray alloc] init];
    NSLog(@"a &: %p", a);
    NSLog(@"b &: %p", b);
    

    Output:

        a &: 0x100103110
        b &: 0x100103110
    

    This "shared instance" continues to exist even if your strong reference obj is gone, therefore the weak pointer is not set to nil.

    Obviously, [[NSMutableArray alloc] init] cannot return a shared instance.

    0 讨论(0)
提交回复
热议问题