OC内存管理retainCount,dealloc

来源:互联网 发布:天然子结构知乎 编辑:程序博客网 时间:2024/05/16 14:23

main.m

  // insert code here...        /*内存管理*/        //1.为什么要管理内存?        //OC动态语言,需要内存否则会造成内存泄露,一定规模后会造成程序的崩溃        //OC中引入了计数(retainCount),判定对象是否应该被销毁,并回收内存                //2.管理内存的方法        //手动内存管理        //自动引用计数(ARC = Automatic reference counting)                /*         关灯例子:         一间教室,没有人,则关灯      //灯比作对象         甲进入教室,开灯,一人需要照明  //对象初始化,    retainCount = 1         乙进入教室,三人需要照明    //retainCount += 1 retainCount = 2         丙进入教室,三人需要照明    //retainCount += 1 retainCount = 3                  乙离开教室,关灯;(特殊)                  乙离开教室,两人需要照明    //retainCount -= 1 retainCount = 2         丙离开教室,一人需要照明    //retainCount -= 1 retainCount = 1         甲离开教室,无人需要照明,则关灯//retainCount -= 1 retainCount = 0                  0对象销毁,内存回收         */        /*内存管理方法*/                //获取对象引用计数值 :retainCount ,为0对象销毁        //retainCount 仅作为参考,不能录入逻辑计算        //持有对象,计数加1:retain        //释放对象,计数减1:release        //对象销毁方法:dealloc ,重写该方法,释放对象内部的成员变量,该方法永远不要手动调用,当对象retainCount        //为0的时候自动调用                //对象需要内存管理,简单复杂数据类型无需管理内存(对象才需要管理)                Person *person = [[Person alloc]init];        //1        NSLog(@"retain Count =%lu",[person retainCount]);        [person retain];        //2        NSLog(@"retain Count =%lu",[person retainCount]);        [person retain];        //3        NSLog(@"retain Count =%lu",[person retainCount]);        [person release];        //2        NSLog(@"retain Count =%lu",[person retainCount]);        [person release];        //1        NSLog(@"retain Count =%lu",[person retainCount]);        [person release];        //0 销毁:由于悬垂指针的原因,最后为1        NSLog(@"retain Count =%lu",[person retainCount]);

运行结果:

2014-12-16 19:57:27.106 OC-ZP-3(内存管理)[5629:2638686] retain Count =1

2014-12-16 19:57:27.107 OC-ZP-3(内存管理)[5629:2638686] retain Count =2

2014-12-16 19:57:27.107 OC-ZP-3(内存管理)[5629:2638686] retain Count =3

2014-12-16 19:57:27.108 OC-ZP-3(内存管理)[5629:2638686] retain Count =2

2014-12-16 19:57:27.108 OC-ZP-3(内存管理)[5629:2638686] retain Count =1

2014-12-16 19:57:27.108 OC-ZP-3(内存管理)[5629:2638686] Person dealloced.

2014-12-16 19:57:27.108 OC-ZP-3(内存管理)[5629:2638686] retain Count =1

Program ended with exit code: 0




Person.m

#import "Person.h"@implementation Person- (void)dealloc {//调用 任何之前不能写在[super dealloc];因为它已经把所有的都销毁的    NSLog(@"Person dealloced.");    [super dealloc];}@end


0 0
原创粉丝点击