Search code examples
objective-cdealloc

Can this code works without overridden dealloc method (Objective-C)


Manual memory management is used. The following code runs well and no crash occurs. But there is no -(void)dealloc method. Is this code wrong? Should I add -(void)dealloc?

MyClass.h

#import <UIKit/UIKit.h>

@interface MyClass : NSObject {
    @private
        BOOL flag;
        UIView *view;
        UILabel *label;
        UIButton *button;
        UITabBar *tabBar;
        UIWebView *webView;

        UIImageView *imageView;
}

@property (nonatomic, retain) UIView *view;
@property (nonatomic, retain) UILabel *label;
@property (nonatomic, retain) UIButton *button;
@property (nonatomic, retain) UITabBar *tabBar;
@property (nonatomic, retain) UIWebView *webView;

@end

MyClass.m

#import "MyClass.h"

@implementation MyClass

@synthesize view;
@synthesize label;
@synthesize button;
@synthesize tabBar;
@synthesize webView;

- (id)init {
    self = [super init];
    if (self) {
        // Initialization code            

        // Among other code,
        imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 

    }
    return self;
}

// Other methods here.

// But -(void)dealloc is not overridden here in the MyClass.m

@end

If we must add -(void)dealloc for the above code, should it be like this:

Overridden -(void)dealloc

-(void)dealloc {
    [view release];
    [label release];
    [button release];
    [tabBar release];
    [webView release];
    [super dealloc];
}

Update 1

@synthesize added, see above.

Update 2

Didn't put this into another post because this seems rather related issue:

See the above MyClass.m/.h, there is a private ivar (not sure it should be called ivar or field here) UIImageView *imageView;, it has no property for it, no @synthesize, initialization given there, how can we dealloc it? Also [imageView release]; in -(void)dealloc?

Update 3

Do we have to check availability before releasing ivars? That is, instead of [view release];, use this:

if (nil != view) {
    [view release];
}

Solution

  • Yes. You need to implement dealloc.

    You dealloc will look like :

    -(void)dealloc {
        [_view release];
        [_label release];
        [_button release];
        [_tabBar release];
        [_webView release];
    
        [super dealloc];
    }
    

    Any retained/copy property should be released on dealloc.

    Your iVar have no meaning. They do not have the same information as the properties, so you can remove your iVars.

    If you want your properties to be backed up by your iVars you should @synthesize them like:

    @synthesize view = view;
    @synthesize label = label;
    @synthesize button = button;
    @synthesize tabBar = tabBar;
    @synthesize webView = webView;