标签:
内存管理和@property的属性
目录
对象的所有权和内存管理原则
合理解决内存管理带来的问题
自动释放池
对内存管理的理解
内存的管理
对象的所有权和内存管理原则
一个对象和一个函数都可以拥有对类对象的管理权,因此对象和函数需要负责类对象的创建和释放
合理解决内存管理带来的问题(在MRC下,在dealloc上有对拥有对象做释放)
阶段一
MyClass *myClass = [[MyClass alloc] init];
//myClass的行为
[myClass release];
阶段二
-(void)setEngine:(Engine *)newEngine{ engine = newEngine; }
Car *car = [[Car alloc] init];
Engine *engine = [[Engine alloc] init]; //1
[car setEngine:engine]; //1
[engine release]; //0 致使car对象中的engine指向的对象为空
阶段三
对setter的调整:-(void)setEngine:(Engine *)newEngine{ engine = [newEngine retain]; };
存在问题:
Engine *engine1 = [Engine new]; //1
[car setEngine:engine1]; //2
[engine1 release]; //1
Engine *engine2 = [Engine new]; //1
[car setEngine:engine2]; //1
[car release]; //1 此时engine1没有被释放掉,即car原来指向的对象没有被释放
阶段三
继续对setter的调整:-(void)setEngine:(Engine *)newEngine{ [engine release]; engine = [newEngine retain]; }
存在问题
Engine *engine = [Engine new]; //1
Car *car1 = [Car new];
Car *car2 = [Car new];
[car1 setEngine: engine]; //2
[engine release]; //1
[car2 setEngine:[car1 engine]]; //出错 此时engine的引用计数为0,car1和car2都不能使用其engine属性
阶段四
继续对setter的调整:-(void)setEngine:(Engine *)newEngine{ [newEngine retain]; [engine release]; engine = newEngine; }
自动释放池
@property的属性
标签:
原文地址:http://www.cnblogs.com/IOS-Developer/p/4178095.html