IPhone Memory Management: What do I need to release inside dealloc?
So say in my viewcontroller's .h file I have:
@interface MyViewController : UIViewController {
IBOutlet UILabel *myLabel;
IBOutlet UIView *myView;
IBOutlet UIImageView *myImageView;
IBOutlet UIButton *myButton;
NSNumber *myNumber;
NSString *myString;
NSMutableArray *myArray;
UILabel *myCurrentLabel;
SomeObject *myObject;
CGPoint myPoint;
}
... now in the viewcontroller's .c file
- (void)dealloc {
[myLabel release];
[myView release];
[myImageView release];
[myButton release];
[myNumber release]; // is this necessary?
[myString release]; // is this necessary?
[myArray release];
[myCurrentLabel release];
[myObject release];
// I don't need to release myPoint because it's a struct
[super dealloc];
}
Please see my comments in the .c file, I'm ju开发者_运维知识库st wondering if my release statements are correct (and if not, why)...
Thank you!!
Without seeing your init code, it is impossible to tell. As a general rule, you need to release anything that you init that is not autoreleased. For example:
//AUTORELEASED
NSArray *array1 = [NSArray arrayWithObject:@"foo"];
// NOT AUTORELEASED
NSArray *array2 = [[NSArray alloc] initWithObject:@"foo"];
// AUTORELEASED
NSArray *array3 = [[[NSArray alloc] initWithObject:@"foo"] autorelease];
In the above 3, you would only have to release array2 if you do not replace them with any other code later on.
NSNumber and NSString are objective-c classes and you can release their instances. However whether you actually need to do that depends on whether you take ownership of the objects when assigning value to them (that is - whether you retain the value) or not.
So you release an object only if you retained it previously (or obtained it using methods containing alloc, new or copy - as per naming guidelines) either explicitly or via property with retain or copy attribute.
In general, I think, you must retain your ivars to be sure that their values will be valid through object's lifetime so release will almost certainly will appear in my classes' dealloc method :)
If you're using properties, use property syntax and set them to nil
in dealloc; the setter will do the "right thing" according to whether the property is declared retain/copy and assign.
Release what you own. Be careful about dangling pointers for things you don't own.
You really need to read the Memory Management Programming Guide for Cocoa before doing anything else.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
精彩评论