#import <Foundation/Foundation.h>
#import "Cpu.h"
#import "Computer.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
#if 0//为什么要retain
Cpu * cpu=[[Cpu alloc]init];
Computer * computer=[[Computer alloc]init];
[computer setCpu:cpu];
[[computer cpu]description];
[cpu release];
[[computer cpu]description];
[computer release];
#endif
#if 0
//为什么要release
Cpu * cpu=[[Cpu alloc]init];
Computer * computer=[[Computer alloc]init];
[computer setCpu:cpu];
Cpu * cpu2=[[Cpu alloc]init];
[computer setCpu:cpu2];
[cpu2 release];
[cpu release];
[computer release];
#endif
Cpu * cpu=[[Cpu alloc]init];
Computer * computer=[[Computer alloc]init];
[computer setCpu:cpu];
[cpu release];
[computer setCpu:cpu];
}
return 0;
}
#import <Foundation/Foundation.h>
@class Cpu;
@interface Computer : NSObject
{
Cpu * _cpu;//此时_cpu指向是nil
}
-(void)setCpu:(Cpu *)cpu;
-(Cpu *)cpu;
@end
#import "Computer.h"
@implementation Computer
-(void)setCpu:(Cpu *)cpu
{
if (_cpu!=cpu) {
[_cpu release];
_cpu=[cpu retain];
}
}
-(Cpu *)cpu
{
return _cpu;
}
-(void)dealloc
{
//一般全局的成员变量在dealloc里release
[_cpu release];
[super dealloc];
}
@end