Objective-C中的@property的retain写法的原理

目的:解决参数是OC对象的内存泄漏 
场景1:在main中参数对象只有一个

=============main.m==================

#import “Person.h”

int main(){

Person *Sam = [Person new];

Car *bmw = [Car new];

[Sam setCar:bmw];

[Sam FuckCar];

[bmw release]; //进行对象回收

//创建了新的一辆车子

Car * landrover= [Car new];

[Sam setCar:landrover];

[Sam FuckCar];

[landrover release]; //进行对象回收

[Sam release] ; }

=======Person.m=============

@implementation

-(void)setCar:(Car *)car{

_car = [_car retain]; }

-(void)FuckCar{

[_car rrun];  }

-(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{

[_car rrun];  }

-(void)dealloc{   // 内存回收后的“遗言”

[_car release];

NSlog(@“Sam is dead!”) ;

[super dealloc]; }

@end

在新增对象参数之前把旧的对象删除,

场景3:如果对象参数是一个,但是连续传入两次,导致对象的retainCount=0的时候再次retain会造成僵尸对象复活,解决

=============main.m==================

#import “Person.h”

int main(){

Person *Sam = [Person new];

Car *bmw = [Car new];

[Sam setCar:bmw];

[Sam FuckCar];

[bmw release]; //进行对象回收

[Sam setCar:bmw];

[Sam FuckCar];

[Sam release] ; }

================Person.m============

@implementation

-(void)setCar:(Car *)car{

//如果是同一个对象不需要retain和release

if(_car != car){

[_car release];   

_car = [_car retain];  }  }

-(void)FuckCar{

[_car rrun];  }

-(void)dealloc{   // 内存回收后的“遗言”

[_car release];

NSlog(@“Sam is dead!”) ;

[super dealloc]; }

@end



最终版本的写法就是:@property(nonatomic,retain)Car *car;的语法格式

你可能感兴趣的:(内存泄露,内存管理,retain,对象,Objective-C)