@autoreleasepool內存管理

雖然OC提供了@autoreleasepool這樣方便快捷管理內存的方案,但它並不像Java一樣能夠全自動化,很多時候還是需要我們自己手動釋放內存。自動釋放池是OC裏面的一種內存回收機制,一般可以將一些臨時變量添加到自動釋放池中,統一回收釋放,當自動釋放池銷燬時,池裏面的所有對象都會調用一次release,也就是計數器會減1,但是自動釋放池被銷燬了,裏面的對象並不一定會被銷燬。

 

#import <Foundation/Foundation.h>

@interface Student :NSObject

@property (nonatomic,assign)int age;

+(id)student;

+(id)studentWithAge:(int)age;

@end



#import "Student.h"

@implementation Student

+(id)student{

    return [[[Studentalloc]init]autorelease];

}

+(id)studentWithAge:(int)age{

    //Student *stu=[Student student];

    Student *stu=[self student];  //self指向當前類

    stu.age=age;

    return stu;

}

@end


#import <Foundation/Foundation.h>

#import "Student.h"

int main(int argc,const char * argv[])

{


    //創建自動釋放池

    @autoreleasepool {

             Student *stu=[Studentstudent];

        

    }

    return 0;

}




OC對象發送一條autorelease消息,就會把這個對象添加到最近的自動釋放池中也就是棧頂釋放池中,Autorelease實際上是把對release的調用延遲了,對於每一次autorelease,系統只是把對象放入了當前的autorelease pool中,當pool被釋放時,pool中所有的對象都會被調用release。

 

 


注意:

1.在ARC下,不能使用[[NSAutoreleasePoolalloc]init](在5.0以前可以使用),而應該使用@autoreleasepool

2.不要把大量循環放在autoreleasepool中,這樣會造成內存峯值上升,因爲裏面創建的對象要等釋放池銷燬了才能釋放,這種情況應該手動管理內存。

3.儘量避免大內存使用該方法,對於這種延遲釋放機制,儘量少用

4.SDK中利用靜態方法創建並返回的對象都已經autorelease,不需要我們自己手動release。


發佈了53 篇原創文章 · 獲贊 3 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章