4

If a UIviewController subclass is created, the method 'dealloc' is created automatically for you.

- (void)dealloc{}

However, when I create a Objective-C Class, the method is not auto-created. Is it necessary to add the dealloc method so that I can release the properties in the class? Especially if I have retained them in the header file?

For example in my Objective-C class header file I have

@interface ClassA : NSObject 
{
    NSString *someProperty;
    UINavigationController *navcon;
}

@property (nonatomic, retain) NSString *someProperty;
@property (nonatomic, retain) UINavigationController *navcon;

Do I need to manually create a dealloc method to release the properties as below?

-(void)dealloc
{
    [someProperty release];
    [navcon release];
}
Zhen
  • 12,361
  • 38
  • 122
  • 199
  • 1
    dont forget to add a call to [super dealloc] in your dealloc method! – Cam Saul Feb 27 '12 at 23:10
  • Note that when using ARC, calling `[super dealloc]` will result in an error. The compiler takes care of it for you. – Eric Jan 16 '13 at 20:28

2 Answers2

6

Yes you must.

dealloc is called upon your object before it is destroyed for good and its memory is returned to the OS. If it holds onto other objects, such as in your case, it is important for those objects to be released too.

That's why you need to override dealloc and release any resource you are holding to there.

The fact that some Xcode template may or may not provide you with a sample implementation of dealloc is irrelevant.

Jean-Denis Muys
  • 6,772
  • 7
  • 45
  • 71
1

You're responsible for releasing all of the top-level objects in the view controller's nib file. -dealloc is a common place to do so.

NSResponder
  • 16,861
  • 7
  • 32
  • 46