nsobject dealloc从未调用过

时间:2013-03-12 22:52:39

标签: iphone objective-c xcode automatic-ref-counting dealloc

我在for循环的每次迭代中创建一个对象。但是,从不调用dealloc函数。是不是应该在每次迭代时发布?我正在使用ARC,我已停用NSZombies。我没有看到任何循环引用。从xcode运行内存泄漏工具它不会显示任何泄漏,但是类的指针内存永远不会被释放,dealloc调用永远不会完成。知道为什么会这样吗?

谢谢!

for(int i=0; i<10; i++)
{
    //calculate the hog features of the image
    HogFeature *hogFeature = [self.image obtainHogFeatures];
    if(i==0) self.imageFeatures = (double *) malloc(hogFeature.totalNumberOfFeatures*sizeof(double));

    //copy the features
    for(int j=0; j<hogFeature.totalNumberOfFeatures; j++)
        self.imageFeatures[i*hogFeature.totalNumberOfFeatures + j] = hogFeature.features[j];
}

HogFeature类声明如下所示:

@interface HogFeature : NSObject

@property int totalNumberOfFeatures;
@property double *features; //pointer to the features 
@property int *dimensionOfHogFeatures; //pointer with the dimensions of the features

@end

和实施:

@implementation HogFeature

@synthesize totalNumberOfFeatures = _totalNumberOfFeatures;
@synthesize features = _features;
@synthesize dimensionOfHogFeatures = _dimensionOfHogFeatures;

- (void) dealloc
{
    free(self.features);
    free(self.dimensionOfHogFeatures);
    NSLog(@"HOG Deallocation!");
}

@end

最后,obtainHogFeatures类别中对UIImage的调用如下:

- (HogFeature *) obtainHogFeatures
{
    HogFeature *hog = [[HogFeature alloc] init];
    [...]
    return hog;
}

2 个答案:

答案 0 :(得分:1)

您可能希望用@autoreleasepool { ... }括起内部循环,告诉编译器何时进行处理,否则只有当控制返回主循环时才会清空池。

for (i = 0; i < 10; i++) {
    @autoreleasepool {
        ...
    }
}

CodeFi在评论中指出: 这将为循环的每次迭代创建一个新的自动释放池,这将在迭代完成后销毁每个对象,但会使程序执行更多工作。如果你不介意在循环完成之前所有的对象都悬空,你可以将@autoreleasepool放在外循环之外

@autoreleasepool {
    for (i = 0; i < 10; i++) {
        ...
    }
}

答案 1 :(得分:0)

物体粘附的原因是因为它们没有被释放。我没有看到self.imageFeatures的声明 - 这是一个数组吗?如果要将特征放入数组中,只要它们保留在数组中或者数组本身未释放,它们就不会被释放。

我对使用C malloc和(尝试)免费电话感到有些困惑。这里可能很有动力,我不知道,但是,鉴于你提供的内容,我将如何写这个,如果没有按预期触发deallocs,我会感到惊讶:

    NSMutableArray *features = [[NSMutableArray alloc] init];

    for (int i = 0; i < 10; i++)
    {
        NSArray *hogFeatureArray = [[self image] obtainHogFeatures];
        for (HogFeature *feature in hogFeatureArray)
        {
            [features addObject:hogFeature];
        } 
    }

    [self setImageFeatures:features];

imageFeatures属性为:

@property (nonatomic, retain) NSMutableArray *imageFeatures;

假设您已将所有生猪特征实例放入此imageFeatures数组中,则它们将由该imageFeatures数组保留。为了观察你的dealloc在行动中,需要发生以下两件事之一:你需要从数组中删除一个hog功能,或者你需要释放数组本身(这可以通过将指针设置为nil来完成):

[self setImageFeatures:nil] // Previously assigned array now released
[[self imageFeatures] removeAllObjects]; // Works alternatively