RGML
RGML

Reputation: 3449

Releasing objects hasn't been released yet on Objective-C

I'm trying to create a method to release the objects I haven't released for any reason yet. I add this on my ViewController's dealloc method:

for (id object in [self.view subviews]){
    NSLog(@"/n") ;
    NSLog(@"%@", object) ;

    if([object isKindOfClass:[UIView class]]){
        if (malloc_size(object)>0) {
            NSLog(@"-> Releasing object with size: %zd", malloc_size(object)) ;    
            [object release] ;
        }
    }
}

Unfortunately, the application crashes. What am I doing wrong?

Upvotes: 1

Views: 92

Answers (3)

El Developer
El Developer

Reputation: 3346

With views most of the times you first have to remove the views from the superview, otherwise you are releasing an object that the superview still needs or keeps reference to.

And you shouldn't be doing this, you should take good balance between your retains and releases.

As an extra and that is something I really don't know: Is it correct to use malloc_size?

Upvotes: 1

JustSid
JustSid

Reputation: 25318

You release the object that is probably already released and only retained by the view that holds it as subview. As your release doesn't remove the view from its superview, you end up with an dead object in your view hierarchy. This will crash either when the view gets deallocated, or when it redraws all its subviews.

Upvotes: 1

Caleb
Caleb

Reputation: 124997

What am I doing wrong?

You're not balancing your retains and releases. You should never need code like that in your example. If you retain something, release it when you're done with it. Anything else is begging for trouble.

In this code specifically, you're releasing all your view's subviews. Did your code retain each and every one of those views? If no, you shouldn't be releasing them. If yes, why? Are you keeping separate references to each one? Your view will retain any views that you add as subviews; you only need to retain them if you have other references to them (and some people choose not to retain even then).

Upvotes: 4

Related Questions