OC內存管理-黃金法則

一、內存管理-黃金法則app

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。spa

類型定義:對象

  基本類型:任何C的類型,如:int、short、char、long、struct、enum、union等屬於基本類型或者結構體;blog

  內存管理對於C語言基本類型無效;繼承

  任何繼承與NSObject類的對象都屬於OC類型。內存

  全部OC對象都有一個計數器,保留着當前被引用的數量。編譯器

內存管理對象:it

  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來明確釋放對象,也就是遞減計數器。

………………

附加代碼

………………

 二、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,和以前拷貝的數據徹底脫離關係。

相關文章
相關標籤/搜索