Objective-C代码没有释放内存!

时间:2009-11-19 07:02:59

标签: objective-c memory-leaks

我正在尝试学习Objective-C。我几乎完成了一个练习,但它没有释放内存:

这就是我所拥有的:

void PrintPolygonInfo() {
    NSLog(@"--------------------");
    NSLog(@" PRINT POLYGON INFO");
    NSLog(@"--------------------");
    NSMutableArray *array = [[NSMutableArray alloc] init];
    PolygonShape *p1 = [[PolygonShape alloc] initWithNumberOfSides:4 minimumNumberOfSides:3 maximumNumberOfSides:7];
    PolygonShape *p2 = [[PolygonShape alloc] initWithNumberOfSides:6 minimumNumberOfSides:5 maximumNumberOfSides:9];
    PolygonShape *p3 = [[PolygonShape alloc] initWithNumberOfSides:12 minimumNumberOfSides:9 maximumNumberOfSides:12];
    [array addObject:p1];
    [array addObject:p2];
    [array addObject:p3];
    // Log the descriptions
    for (id shape in array) {
        NSLog(@"%@", shape);
    }
    // Test the constraints
    for (PolygonShape *shape in array) {
        [shape setNumberOfSides:10];
    }
    [p1 release];
    [p2 release];
    [p3 release];
}

这是dealloc():

- (void) dealloc {
    NSLog(@"Deallocated!!!");
    [super dealloc];
}

这就是结果:

2009-11-19 06:58:17.030 Assignment 1B[5441:a0f] --------------------
2009-11-19 06:58:17.030 Assignment 1B[5441:a0f]  PRINT POLYGON INFO
2009-11-19 06:58:17.031 Assignment 1B[5441:a0f] --------------------
2009-11-19 06:58:17.031 Assignment 1B[5441:a0f] init: Retain count of 1.
2009-11-19 06:58:17.032 Assignment 1B[5441:a0f] init: Retain count of 1.
2009-11-19 06:58:17.032 Assignment 1B[5441:a0f] init: Retain count of 1.
2009-11-19 06:58:17.033 Assignment 1B[5441:a0f] Hello I am a 4-sided polygon (aka a Square) with angles of 90 degrees (1.570796 radians).
2009-11-19 06:58:17.033 Assignment 1B[5441:a0f] Hello I am a 6-sided polygon (aka a Hexagon) with angles of 120 degrees (2.094395 radians).
2009-11-19 06:58:17.034 Assignment 1B[5441:a0f] Hello I am a 12-sided polygon (aka a Dodecagon) with angles of 150 degrees (2.617994 radians).
2009-11-19 06:58:17.034 Assignment 1B[5441:a0f] Invalid number of sides: 10 is greater than the maximum of 7 allowed
2009-11-19 06:58:17.035 Assignment 1B[5441:a0f] Invalid number of sides: 10 is greater than the maximum of 9 allowed

如您所见,它不会打印'Deallocated !!!'消息:

有人可以告诉我,我做错了吗?

提前致谢

3 个答案:

答案 0 :(得分:7)

数组保留它包含的对象。只有从数组中删除对象或释放数组后,才能释放对象。

答案 1 :(得分:2)

你正在泄漏阵列。您使用alloc / init创建它,但从不发布它。可以release,也可以使用[NSMutableArray array]创建。

此外,在释放对象时会调用dealloc方法。但是,看起来你正在使用一个函数(不是一个对象的方法)来做这些事情。你的代码的其余部分是如何设置的?

答案 2 :(得分:1)

请注意,如果您的应用程序终止,则可能不会调用dealloc方法。无论如何应用程序的内存都被清除,OSX可能会决定更快地终止应用程序并清除内存而不通过所有deallocs。

NSObject reference中记录了这一点。