IOS知識分享:OC記憶體管理(黃金法則)
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,和之前拷貝的資料完全脫離關係。