Bao Xiaopeng
Bao Xiaopeng

Reputation: 23

With ARC , why the dealloc not called

I have enable the ARC. but this code makes me wonder

@interface Dog : NSObject
@end

@implementation Dog

- (void)dealloc
{
    printf("Dog is dealloc\n"); //the function not called
}

@end


@interface Person : NSObject
@property (nonatomic, strong) Dog *dog;
@end

@implementation Person

- (void)dealloc
{
    printf("Person is dealloc\n");
    _dog = nil;
}

-(Dog *)dog
{
    return _dog;
}

@end

int main()
{
    Person *p = [[Person alloc] init];
    p.dog = [[Dog alloc]init];
    Dog* d = p.dog;
    d=nil;
    p=nil;
    printf("end\n");

    return 0;
}


the result is

Person is dealloc

end

Program ended with exit code: 0

why the dog's dealloc method not called. and then I commented out this Method, the dog's dealloc method called.

//-(Dog *)dog
//{
//    return _dog;
//}

thank you very much.

Upvotes: 2

Views: 71

Answers (1)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119932

You can see the memory graph to find out what exactly points to the Dog and preserve it from automatically deallocation:

Memory graph1

Unlike Swift, In Objective-C, you need to put the main body inside an @autoreleasepool to make it ARC compatible:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        Person *p = [[Person alloc] init];
        p.dog = [[Dog alloc]init];
        Dog* d = p.dog;
        d = nil;
        p = nil;
        printf("Ended...\n");
    }
    return 0;
}

Then you will see this in the output:

Person is dealloc
Ended...
Dog is dealloc

Upvotes: 1

Related Questions