简体   繁体   中英

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 just 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM