4
votes

I'm trying to get the dealloc method to run on some items that are/were stored in a mutable array, but can't seem to find a way to make it happen.

I ran into this problem while working in a larger ARC project and found an answer in this post: dealloc method is not invoked when set an object to nil. After reading that answer I felt I understood how ARC should be handling the code in question (below), however after running it in a very simple test project I get the same results.

In the main view controller I init a mutable array (a strong property) and add some other view controllers to it. I then remove all objects:

- (void)viewDidLoad{
    [super viewDidLoad];

    containerArray = [[NSMutableArray alloc]init];
    for(int i = 0; i < 10; i++){

        //item +1 (item at +1)
        Item *item = [[Item alloc]initWithNibName:nil bundle:nil];

        //item +1 (item at +2)
        [containerArray addObject:item];

        //ARC should release item -1 (item at +1...I think)
    }

    //removeAllObjects should release each item -1 (item(s) at 0)
    [containerArray removeAllObjects];
    //dealloc should be called...
}

In the Item view controller:

-(void)dealloc{
    NSLog(@"item dealloc");
}

Any help is greatly appreciated.

1

1 Answers

2
votes

After reading your code 3 times, I could not see any flaws in your approach. I thought everything was right, and that dealloc should be called 10 times when you remove all the objects from the array.

Then I decided to try the code, and I just discovered that.... we both were right :) the code is perfect. When I run it I get the item dealloc output 10 times.

  • Are your really sure you are trying it in a ARC project?
  • Is the dealloc inside the Item class?

There is some other thing you are not doing right, but the code and the arguments are correct.