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,和之前拷貝的數據完全脫離關系。