In a non-ARC development environment, dealloc is the last chance to clean up the memory before the class is released. Which variables and attributes should be released? How should some special classes (nstimer, observer) be released. It should be noted that not releasing will cause memory leakage, and excessive release will also cause memory leakage. Next, we will gradually expand:
1. Release of Variable
Variable Declaration
@ Interface EnterHondaViewController: UIViewController {
UIImageView * imageLogo;
UIButton * btn_effecate;
UIButton * btn_Brand;
CorporateView * corporateview;
BrandView * brandview;
}
Variable Initialization
@ Implementation EnterHondaViewController
-(Id) initWithFrame :( CGRect) frame
{
Self = [super init];
If (self ){
Self. view. frame = frame;
[Self. view setBackgroundColor: [UIColor whiteColor];
UIImageView * background = [[UIImageView alloc] initWithFrame: CGRectMake (0, 768,)];
[Self. view addSubview: background];
[Background release];
[Background setImage: [UIImage imageNamed: @ "AllAuto_Image_BG"];
UIButton * backBtn = [[UIButton alloc] initWithFrame: CGRectMake (50, 18, 55,40)];
[BackBtn setImage: [UIImage imageNamed: @ "home_button"] forState: UIControlStateNormal];
[BackBtn addTarget: self action: @ selector (onBack :) forControlEvents: UIControlEventTouchUpInside];
[Self. view addSubview: backBtn];
[BackBtn release];
UILabel * titleLabel = [[UILabel alloc] initWithFrame: CGRectMake (160, 25,400, 35)];
TitleLabel. backgroundColor = [UIColor clearColor];
TitleLabel. textAlignment = NSTextAlignmentLeft;
TitleLabel. font = [UIFont fontWithName: @ "Arial" size: 30];
TitleLabel. textColor = [UIColor colorWithRed: 0.4 green: 0.4 blue: 0.4 alpha: 1.0];
[Self. view addSubview: titleLabel];
[TitleLabel release];
[TitleLabel setText: @ ""];
UIImageView * lineView = [[UIImageView alloc] initWithFrame: CGRectMake (frame. size. width-658)/658, 8)];
LineView. image = [UIImage imageNamed: @ "AllAuto_Config_TimeLine_BG"];
[Self. view addSubview: lineView];
[LineView release];
UIView * logoview = [[UIView alloc] initWithFrame: CGRectMake (780, 80,240, 25)];
[Self. view addSubview: logoview];
[Logoview release];
ImageLogo = [[UIImageView alloc] initWithFrame: CGRectMake (0, 6, 12, 13)];
[Logoview addSubview: imageLogo];
[ImageLogo release];
ImageLogo. image = [UIImage imageNamed: @ "allauto_configuration_button_select"];
Btn_effecate = [[UIButton alloc] initWithFrame: CGRectMake (13, 0,100, 25)];
[Logoview addSubview: btn_gateate];
Btn_Corporate.tag = 1;
[Btn_release];
[Btn_effecate addTarget: self action: @ selector (onOptionClick :) forControlEvents: UIControlEventTouchUpInside];
[Btn_policate setTitle: @ "Corporate Culture" forState: UIControlStateNormal];
Btn_Brand = [[UIButton alloc] initWithFrame: CGRectMake (133, 0,100, 25)];
[Logoview addSubview: btn_Brand];
Btn_Brand.tag = 3;
[Btn_Brand release];
[Btn_Brand addTarget: self action: @ selector (onOptionClick :) forControlEvents: UIControlEventTouchUpInside];
[Btn_Brand setTitle: @ "brand story" forState: UIControlStateNormal];
Corporateview = [[CorporateView alloc] initWithFrame: CGRectMake (0,110, frame. size. width, frame. size. height-120)];
Brandview = [[BrandView alloc] initWithFrame: CGRectMake (0,110, frame. size. width, frame. size. height-110)];
[Btn_effecate sendActionsForControlEvents: UIControlEventTouchUpInside];
[[Nsicationicationcenter defacenter center] addObserver: self selector: @ selector (onGoBrandPage :) name: icationication_navigate_to_brand object: nil];
}
Return self;
}
Variable release
-(Void) dealloc
{
[[Nsicationcenter center defacenter center] removeObserver: self];
[Brandview release];
[Corporateview release];
[Super dealloc];
}
2 release of attributes
Attribute Declaration
@ Interface GGDetailCell: UIGridViewCell {
}
@ Property (nonatomic, retain) UILabel * labelTitle;
@ End
Attribute Initialization
-(Id) init {
If (self = [super init]) {
Self. frame = CGRectMake (0, 0, 66, 30.5 );
{// LabelTitle
Self. labelTitle = [[[UILabel alloc] initWithFrame: CGRectMake (0, 7, 66, 16)] autorelease];
[Self. labelTitle setBackgroundColor: [UIColor clearColor];
[Self. labelTitle setTextColor: TEXT_COLOR_PART_NORMAL];
[Self. labelTitle setFont: [UIFont systemFontOfSize: 12];
[Self. labelTitle setNumberOfLines: 0];
[Self. labelTitle setTextAlignment: UITextAlignmentCenter];
[Self addSubview: self. labelTitle];
}
}
Return self;
}
Attribute release
-(Void) dealloc {
Self. labelTitle = nil;
[Super dealloc];
}
3. Release the timer
Timer declaration:
@ Interface BRLandscapeView
Nstmer * timer;
}
@ End
Regular initialization:
-(Void) myInit {
{// Set timer
Timer = [nst1_scheduledtimerwithtimeinterval: 1
Target: self
Selector: @ selector (handleTimer :)
UserInfo: nil
Repeats: YES];
}
Release Timer: If the initialization is declared in the view, release the timer before releasing the view in the controller. Otherwise, the timer cannot be released due to loop reference.
@ Implementation BookReadController
-(Void) dealloc
{
If (landscape ){
[Landscape-> timer invalidate];
}
Saferelscape (landscape );
[Super dealloc];
}
@ End
4. Release notification
-(Void) dealloc
{
[[Nsicationcenter center defacenter center] removeObserver: self];
[Super dealloc];
}
5. Release of delegate
The delegate attribute value is generally self. Although the assign is declared, the delegate attribute is released before the related view is released.
Scenario 1
If (_ loadingContentView ){
_ LoadingContentView. delegate = nil;
[_ LoadingContentView removeFromSuperview];
}
Case 2
Self. partGridView. uiGridViewDelegate = nil;
Self. partGridView = nil;
6 memory management of functions with return values
If a function requires a return value, the return value is declared and initialized in the function, but cannot be released immediately if it is missing, the best solution is as follows:
-(NSArray *) getTemplatesByPath :( NSString *) path
{
NSError * error = nil;
NSArray * files = [fileManager contentsOfDirectoryAtPath: path error: & error];
If (error! = Nil)
Return nil;
NSMutableArray * resultArray = [NSMutableArray new];
For (NSInteger index = 0; index <[files count]; index ++)
{
NSString * fileName = [files objectAtIndex: index];
NSString * extType = [fileName pathExtension];
If (NO = [extType isEqualToString: @ "tpl"])
Continue;
[ResultArray addObject: fileName];
}
Return [resultArray autorelease];
}
Extension
1. The variable can be released immediately after initialization.
UIImageView * lineView = [[UIImageView alloc] initWithFrame: CGRectMake (frame. size. width-658)/658, 8)];
LineView. image = [UIImage imageNamed: @ "AllAuto_Config_TimeLine_BG"];
[Self. view addSubview: lineView];
[LineView release];
2. Whether it is declared as a variable or an attribute.
In the first version of ios, we declared both attributes and underlying instance variables for the output port. At that time, attributes were a new mechanism of the oc language, you must declare the corresponding instance variables, for example:
@ Interface MyViewController: UIViewController
{
UIButton * myButton;
}
@ Property (nonatomic, retain) UIButton * myButton;
@ End
Recently, Apple switched the default compiler from GCC to LLVM (low level virtual machine), and no longer needed to declare instance variables for attributes.
If LLVM finds an attribute that does not match the instance variable, it automatically creates an instance variable starting with the following line. Therefore, in this version, we no longer declare instance variables for the output port.
For example:
MyViewController. h file
@ Interface MyViewController: UIViewController
@ Property (nonatomic, retain) UIButton * myButton;
@ End
In the MyViewController. m file
The compiler automatically generates an instance variable _ myButton.
In the. m file, you can directly use the _ myButton instance variable, or use the self. myButton. attribute to make it the same.
Note that self. myButton is actually the getter/setter method of the myButton attribute called.
This is different from the usage of the midpoint in c ++. The vertex in c ++ can directly access the member variable (that is, the instance variable)
For example, the following code is available in oc:
. H file
@ Interface MyViewController: UIViewController
{
NSString * name;
}
@ End
In the. m file
An expression like self. name is incorrect. Xcode will prompt you to use-> and change it to self-> name.
Because the oc midpoint expression is used to call the method, but the above Code does not have the name method.
Oc Syntax:
"The dot expression (.) seems to be a bit similar to the structure access in C language and the Object Access in java language summary. In fact, this is what the oc designer intends to do.
If the dot expression appears on the left side of equal sign =, the setter method of the attribute name will be called. If the dot expression appears on the right, the getter method of the attribute name will be called. "
The dot expression in oc is actually a shortcut to call the setter and getter methods of the object, for example:
Dealie. blah = greeble is fully equivalent to [dealie. blab setBlah: greeble];
In previous usage, declare the instance variables corresponding to the attributes:
@ Interface MyViewController: UIViewController
{
UIButton * myButton;
}
@ Property (nonatomic, retain) UIButton * myButton;
@ End
This method is basically the most widely used, and most of it is currently in use, because many open-source codes use this method.
However, after ios5 is updated, Apple recommends using the following methods:
@ Interface MyViewController: UIViewController
@ Property (nonatomic, retain) UIButton * myButton;
@ End
Because the compiler will automatically generate the instance variable _ myButton starting with the following line. You do not need to manually write instance variables.
In addition, you do not need to write @ synthesize myButton in the. m file; the setter and getter methods are automatically generated for you.
@ Synthesize: Let the compiler automatically generate the setter and getter methods for you.
It also serves to specify the instance variables corresponding to the attributes,
For example, @ synthesize myButton = xxx;
So self. myButton is actually the instance variable xxx for the operation, rather than _ myButton.
In actual projects, we generally write. m files like this.
@ Synthesize myButton;
After this is written, the compiler will automatically generate the myButton instance variables and the corresponding getter and setter methods.
Note: The instance variable _ myButton does not exist because the automatically generated instance variable is myButton rather than _ myButton.
So now @ synthesize is equivalent to specifying instance variables,
If @ synthesize myButton is written in the. m file, the generated instance variable is myButton.
If @ synthesize myButton is not written, the generated instance variable is _ myButton.
Therefore, it is slightly different from the previous usage.
Note: This attribute must be distinguished from the attribute added in the category, because only methods can be added to the category, and instance variables cannot be added.
Attributes are often added to categories in ios code. In this case, instance variables are not automatically generated.
For example
The UIViewController class is extended in the UINavigationController. h file.
@ Interface UIViewController (UINavigationControllerItem)
@ Property (nonatomic, readonly, retain) UINavigationItem * navigationItem;
@ Property (nonatomic) BOOL hidesBottomBarWhenPushed;
@ Property (nonatomic, readonly, retain) UINavigationController * navigationController;
@ End
The attributes added here will not automatically generate instance variables. The attributes added here are actually the added getter and setter methods.
Note that anonymous classes (anonymous extension) can be used to add instance variables. Non-Anonymous classes cannot be used to add instance variables. You can only add methods or attributes (actually, they are also methods ).
ARC
For strong references and weak references, you can view the full guide to ios5arc.
The arc introduced by ios5 is indeed much more convenient, and the ARC rules are very simple:
As long as there is another variable pointing to the object, the object will remain in the memory. When the pointer points to a new value or the pointer no longer exists, the associated object is automatically released.
This rule applies to instance variables, synthesize attributes, and local variables.
In the past, when there was no arc, you must call
Dealloc method to release memory, for example:
-(Void) dealloc {
[_ MyTableView release];
[Superdealloc];
}
If ARC is used, the dealloc method is no longer required, and the release issue is no longer required. The system automatically manages the memory.