内存管理-黄金法则

1、内存管理-黄金法则

The basic rule to apply is everything that increases the reference counter with alloc, [mutable]copy[withZone:] or retain is in charge of  the corresponding  [auto]release.

如果对一个对象使用了alloc、[mutable]copy、retain,那么你必须使用相应的release或者autorelease。

类型定义:

  基本类型:任何C的类型,如:int、short、char、long、struct、enum、union等属于基本类型或者结构体;

  内存管理对于C语言基本类型无效;

  任何继承与NSObject类的对象都属于OC类型。所有OC对象都有一个计数器,保留着当前被引用的数量。

内存管理对象:

  OC的对象:凡是继承于NSObject;

  每一个对象都有一个retainCount计数器。表示当前的被应用的计数。如果计数为0,那么就真正的释放这个对象。

alloc、retain、release函数:

  1)alloc 函数是创建对象使用,创建完成后计数器为1;只用1次。

  2)retain是对一个对象的计数器+1;可以调用多次。

  3)release是对一个对象计数器-1;减到0对象就会从内存中释放。

 增加对象计数器的三种方式:

  1)当明确使用alloc方法来分配对象;

  2)当明确使用copy[WithZone:]或者mutableCopy[WithZone:]copy对象的时;

  3)当明确使用retain消息。

上述三种方法使得计数器增加,那么就需要使用[auto]release来明确释放对象,也就是递减计数器。

………………

附加代码

………………

 2、retain点语法

OC内存管理正常情况要使用大量的retain和release操作;

点语言可以减少使用retain和release的操作。

编译器对于retain展开形式:

  @property (retain)Dog *dog;

  展开为:-(void) setDog:(Dog *)aDog;

      -(Dog *)dog;

  @synthesize dog = _dog;  //(retain属性)

  展开为:-(void) setDog:(Dog *)aDog{

        if(_dog != aDog){

          [_dog release];

          _dog = [aDog retain];

        }

      };

      -(Dog *)dog{

        return _dog;

      };

copy属性:copy属性是完全把对象重新拷贝一份,计数器重新设置为1,和之前拷贝的数据完全脱离关系。

 

 
 
原文地址:https://www.cnblogs.com/iOS-mt/p/4121793.html