//// main.m#import#import "Pet.h"#import "Person.h"#import "SuperMan.h"int main(int argc, const char * argv[]) { @autoreleasepool { Person *per = [[Person alloc]init]; [per test]; NSUInteger r = [per retainCount]; NSLog(@"%lu",r); [per release]; SuperMan *sm = [[SuperMan alloc]init]; Pet *pet = [[Pet alloc]init]; [sm setPet:pet]; [sm test]; [sm release]; [pet release]; } return 0;}
//// Person.h#import#import "Pet.h"@interface Person : NSObject{ Pet *_pet;//初始化}-(void)test;@end//// Person.m#import "Person.h"@implementation Person-(instancetype)init{ if (self=[super init]) { self->_pet = [[Pet alloc]init]; } return self;}-(void)test{ if (_pet) { [_pet play]; }}-(void)dealloc{ NSLog(@"释放"); [_pet release]; [super dealloc];}@end
//// Pet.h// 关联对象的内存管理#import@interface Pet : NSObject-(void)play;@end//// Pet.m// 关联对象的内存管理#import "Pet.h"@implementation Pet-(void)play{ NSLog(@"play");}-(void)dealloc{ NSLog(@"Pet 释放"); [super dealloc];}@end
//// SuperMan.h#import#import "Pet.h"@interface SuperMan : NSObject{ Pet *_pet;}-(void)setPet:(Pet*)mypet;-(void)test;@end//// SuperMan.m#import "SuperMan.h"@implementation SuperMan-(void)setPet:(Pet*)mypet{ //_pet = mypet; if (_pet!=mypet) { [_pet release]; _pet = [mypet retain]; }}-(void)test{ if (_pet) { [_pet play]; }}-(void)dealloc{ NSLog(@"Super man 释放"); [_pet release]; [super dealloc];}@end