目的:解决参数是OC对象的内存泄漏 场景1:在main中参数对象只有一个
=============main.m================== #import“Person.h” intmain(){ Person *Sam = [Person new]; Car*bmw = [Car new]; [SamsetCar:bmw]; [SamFuckCar]; [bmwrelease]; //进行对象回收 //创建了新的一辆车子 Car * landrover= [Car new]; [Sam setCar:landrover]; [SamFuckCar]; [landrover release]; //进行对象回收 [Samrelease] ; }
=======Person.m============= @implementation -(void)setCar:(Car*)car{ _car = [_carretain]; } -(void)FuckCar{ [_carrrun]; } -(void)dealloc{ // 内存回收后的“遗言” [_car release]; NSlog(@“Sam is dead!”) ; [super dealloc]; } @end //如果对象参数有2个,在dealloc中只能释放一个对象 造成内存泄漏 场景2:对象参数有多个,如果按照场景1就会造成内存泄漏,解决方案 @implementation -(void)setCar:(Car*)car{ [_car release]; //新增了这一句 _car= [_car retain]; } -(void)FuckCar{ [_carrrun]; } -(void)dealloc{ // 内存回收后的“遗言” [_carrelease]; NSlog(@“Samis dead!”) ; [superdealloc]; } @end [size=13.3333330154419px]在新增对象参数之前把旧的对象删除, [size=13.3333330154419px]场景3:如果对象参数是一个,但是连续传入两次,导致对象的retainCount=0的时候再次retain会造成僵尸对象复活,解决 =============main.m================== #import“Person.h” intmain(){ Person*Sam = [Person new]; Car*bmw = [Car new]; [SamsetCar:bmw]; [SamFuckCar]; [bmwrelease]; //进行对象回收 [Sam setCar:bmw]; [Sam FuckCar]; [Samrelease] ; }
================Person.m============
@implementation -(void)setCar:(Car*)car{ //如果是同一个对象不需要retain和release if(_car != car){ [_car release]; _car = [_carretain]; } } -(void)FuckCar{ [_carrrun]; } -(void)dealloc{ // 内存回收后的“遗言” [_carrelease]; NSlog(@“Samis dead!”) ; [superdealloc]; } @end
[size=13.3333330154419px]最终版本的写法就是:@property(nonatomic,retain)Car *car;的语法格式
|