. h file
-----------------------------------------
#import <Foundation/Foundation.h>
#import "Car.h"
@interface Person:nsobject
{
Car *_car;
NSString *_name;
}
-(void) SetName: (NSString *) name;
-(NSString *) name;
-(void) Setcar: (car *) car;
-(car *) car;
-(void) drive;
@end
. m file
-----------------------------------------
#import "Person.h"
@implementation person
-(void) SetName: (NSString *) name{
if (_name!=name) {
Release old value
[_name release];
Retain new value
_name=[name retain];
}
}
-(NSString *) name{
return _name;
}
-(void) Setcar: (Car *) car{
if (_car!=car) {//With this is afraid to pass in the same C1 two times, it will be a wild pointer error
C1=2->c1=1
[_car release];//when the first time C1 came in, because there was no car before, so _car=nil. [Nil release] execution does not error, but also invalid *//When C2 passed in, C1 before the main function has been release once, C1 has been 1, and the current _car is C1, so C2 in time, C1 (_car) release, Retaincount=0, automatic call dealloc destroy, [old value release]
C1 =2->c2=2
_car=[car retain];//When the first C1 came in, c1=1+1=2, when C2 passed in, C2 from 1 to 2, exit, return to main function
}
}
-(Car *) car{
return _car;
}
-(void) drive{
[_car Run];
}
-(NSString *) description{
//
return [NSString stringwithformat:@ "Age is%d", _age];
//}
-(void) dealloc{
Now it's C2, c2=0.
[_car RELEASE];//C2 has been passed in, ("At this time Car" =_car), at this time the _car again release, also destroyed to
[_name release];
NSLog (@ "Person object is destroyed!) "); Print 4:person object is destroyed!
[Super Dealloc];
}
@end
oc-the code in the. h files and. m files in memory management, comments are important