IOS 非ARC开发内存管理的几条规则

关于ios内存管理。在开发过程中,内存管理很重要,我简单说明一下。

1.正确用法

UIView *v = [[UIView allocinit]; //分配后引用计数为1

[self.view addSubview:v];  //这儿引用计数加1,为2

[v release];  //这儿引用计数为1

最后系统在回收self.view的时候,会先回收其subView,所以v会被自动回收

 

2.如果v是类的成员变量,写了如下代码,不需要再在类的dealloc方法里[v release];

v = [[UIView allocinit];

[self.view addSubview:v];

[v release];

如果在dealloc里调用了release,那么就多release了,会crash.

 

3.如果v是类的属性,分两种情况

a. @property (nonatomicassignUIView *v;  这儿是assign, 然后分配内存的时候如果是这样

v = [[UIView allocinit];

[self.view addSubview:v];

[v release];或是这样用

v = [[UIView allocinit];

[self.view addSubview:v];

[v release];  

都不需要在dealloc里[v release];

 

b.@property (nonatomicretainUIView *v;  @property (nonatomiccopyUIView *v;声明的属性,那么这样分配内存

v = [[UIView allocinit];

[self.view addSubview:v];

[v release];这样与a是一样情况,不需要在dealloc里释放。但如果是

self.v = [[UIView allocinit];

[self.view addSubview:v];

[v release];加了个self,那么就要在dealloc里[v release];

原文地址:https://www.cnblogs.com/zhangyuqing/p/3566348.html