1

I had developed an app and now I'm using Instruments to see the memory usage. I have a problem understanding the retain/release process of my object. This is what Instruments says:

The retain count increase when I add my object into an array, when I add it on my view and when I take off from the array. So, when I use removeFromSuperview the object retainCount will never be zero, so the object don't release the memory.

EDIT 1: I forgot to say i'm using ARC.

EDIT 2: I describe exactly what happen : I create the object together other objects in a class called NKLevelGenerator. Into it i alloc the NKIngredients and then i add all to a NSArray which will be returned. Here the retain count of every object is 2. In my NKLevelVC, my ViewController, i use this instruction :

[level addObjectsFromArray:[levelGenerator level1WithDelegate:self ciotola:ciotola bagliore:bagliore difficulty:NKDifficultyHard]];

Object level is a NSMutableArray that i alloc and init in viewDidLoad. From here i call another method which performs this operations :

- (void)insertInArrayRandomly {
    for (int i=0; i<[level count]; i++) {
        [ingredienti insertObject:[level objectAtIndex:[[indexes objectAtIndex:i]integerValue]] atIndex:i];
    }
}

Object ingredienti is another NSMutableArray that I alloc and init in viewDidLoad. indexes is an array of NSInteger which contains random indexes to extract NKIngredient object randomly. Then i'm doing this :

NKIngredient *ing = [ingredienti objectAtIndex:index];
[[self view] insertSubview:ing belowSubview:navBar];
[ing animateIngredient];
[ingredienti removeObject:ing];
4

2 回答 2

1

在查看 Instruments 之前,您是否尝试过代码的静态分析?它可能有助于解决简单的内存问题。

但首先要检查的是:您是否遵循黄金法则

黄金法则是:对于每个alloccopy或者retain你必须使用一个,并且只有一个,release或者autorelease

这是没有 ARC 的内存管理最重要的规则。因此,您的对象被数组保留的事实与您无关,只需记住您保留、分配或复制的内容并释放它即可。

PS:下次,您的代码将比 Instruments 屏幕截图更有帮助。

于 2012-12-19T10:36:40.343 回答
0

首先:使用工具来查看是否有效地存在内存泄漏,为此目的制作了一个工具,它会告诉您泄漏内存的位置。第二:这取决于视图上有多少对象[保留]。如果你添加到一个数组,它会保留视图,但是如果你没有在创建视图的方法中释放它,当你从数组中释放视图时,计数仍然是 1。

于 2012-12-19T10:34:48.447 回答