简体   繁体   中英

Retain cycles and Instruments

I just wrote this retain cycle:

#import <Foundation/Foundation.h>
#import "Driver.h"
#import "Car.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Driver *driver = [[Driver alloc] init];
        Car *car = [[Car alloc] init];

        driver.car = car;
        car.driver = driver;
    }
    sleep(100);
    return 0;
}

Obviously, Driver and Car have strong properties.

Anyway, Instruments is not showing the retain cycle up in Leaks -> Cycles & Roots on Xcode 6.1.

It's a retain cycle, right? What's happening then?

Retain cycles are not leaks. Leak occurs when you lost track (reference) of the object. Since both objects have references to the other, it is not considered as a leak. Retain cycles are harder to find than leaks because of that. It depends on your code, and you should be careful.

Okay, It's working now:

@autoreleasepool {
    Driver *driver = [[Driver alloc] init];
    Car *car = [[Car alloc] init];

    driver.car = car;
    car.driver = driver;

    driver = nil;
    car = nil;

    for (size_t i = 0; i < 100000; i++) {
        driver = [[Driver alloc] init];
        car = [[Car alloc] init];
    }
}

With this code, Instruments shows the cycle on Leaks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM