Pay attention to retain's circular references and use of @ class, retain @ class
One type of retain is circular reference. The so-called circular reference is that two objects contain each other. When you call me, retain once, I also called you once, so no one can be recycled. The solution is to write the @ property parameter to the instance variable (oc object type) in the two objects:
Write @ property (nonatomic, retain) Person * Person;
One write is @ property (nonatomic, assign) Car * Car;
The following code is provided to illustrate the substantive issues:
There are two types of Person and Card. A Person owns a car and a car corresponds to a Person. The Code is as follows:
1) Person. h # import <Foundation/Foundation. h> @ class Car; @ interface Person: NSObject @ property (nonatomic, retain) Car * car; @ end2) person. m # import "Person. h "# import" Car. h "@ implementation Person-(void) dealloc {[_ car release]; NSLog (@" Person object recycled "); [super dealloc] ;}@ end3) Car. h # import <Foundation/Foundation. h> @ class Person; @ interface Car: NSObject @ property (nonatomic, assign) Person * person; @ end4) Car. m # import "Car. h "@ implementation Car-(void) dealloc {NSLog (@" car object recycled "); [super dealloc] ;}@ end5) main. # import <Foundation/Foundation. h> # import "Car. h "# import" Person. h "int main (int argc, const char * argv []) {// P-1 (counter is 1) Person * p = [[Person alloc] init]; // C-1 Car * c = [[Car alloc] init]; // C-2 p. car = c; // P-1. person = p; // C-1 [c release]; // The p-0, c-0 [p release] return 0 ;}
The figure is analyzed as follows:
If both classes are written as @ property (nonatomic, retain) Person * p;
@ Property (nonatomic, retain) Car * c;
Memory during program execution:
After the program ends, the object is not recycled, causing memory leakage.
If the Car. in h, change the retain in the @ property parameter to assign, which means that only the value is assigned. _ person does not need to perform the retain operation. Therefore, when [p release] is executed, the counter of p ranges from 1 to 0, so the object p is recycled and enters the dealloc method of p. Execute [_ car release], and the counter of c starts from 1 to 0; reclaim Object c, and then recycle object p;
So the circular reference solution:
Use retain at one end
Assign
It is worth noting that @ class A is generally used for class B. the h file indicates that Class A is declared in Class B. Of course, it is only A declaration, not copying the attributes and methods of Class. # Import copies all attributes and Methods. If many files have the imoport file, when the header file is modified, many files need to be re-compiled, but @ class is not required. It only needs to be used in class B. # import is allowed in the m file.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.