简体   繁体   English

保持周期和仪器

[英]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. 无论如何,Instruments不会在Xcode 6.1的Leaks-> Cycles&Roots中显示保留周期。

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. 通过此代码,Instruments可以显示泄漏的周期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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