自動釋放池的基本概念 cocoa中有一個自動釋放池(Autorelease Pool)的概念,顧名思義,它是可以存放一些實體的 集合,在這個自動釋放池中的對象,是能夠被自動釋放的。NSObject類提供了一個autorelease 消息,當我們向一個對象發送一個autorelease消息時,這個對象就被放入到自動釋放池。 創建自動釋放池 @autoreleasepool { //入池對5.0之後的寫法 } NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init]; // 入池對5.0之前的寫法 [pool autorelease]; 自動釋放池的銷燬時間 當我們將一個對象發送了autorelease消息時,當子自動釋放池銷燬時,會對池中的每一個對象 發送一條release消息,以此來進行釋放它們。 (一):下面來看實例:創建一個Person實例對象,然後加入到自動釋放池中,向該實例對象發送一條autorelease消息, 來查看一下它的生命週期) @autoreleasepool {//入池對5.0之後的寫法 Person *tom=[[Person alloc]init]; [tom autorelease]; NSLog(@"pool exist"); } NSLog(@"pool dead"); (二):接着上面的例子,向該對象發送一條retain消息,看下聲明週期 @autoreleasepool {//入池對5.0之後的寫法 Person *tom=[[Person alloc]init]; //1 [tom autorelease]; [tom retain]; //2 NSLog(@"pool exist"); NSLog(@"tom %ld",[tom retainCount]); [tom release]; //1 NSLog(@"tom %ld",[tom retainCount]); (三):接着上面的例子,如果有多個自動釋放池的問題,根據發送的autorelease消息來進行判斷是 對象加入的那個自動釋放池, @autoreleasepool {Person *tom=[[Person alloc]init]; //1 @autoreleasepool { //入池對5.0之後的寫法 [tom autorelease]; [tom retain]; NSLog(@"pool exist"); NSLog(@"tom1 %ld",[tom retainCount]); } NSLog(@"pool1 dead"); NSLog(@"tom2 %ld",[tom retainCount]); } NSLog(@"pool2 dead"); 【小結】: 1:自動釋放池的數據結構 自動釋放池是以棧的形式實現,當你創建一個新的自動釋放池,它將會被添加到棧頂。接受autorelease 消息的對象將會唄放入棧頂 2:如何持有對象 當我們使用alloc,copy,retain對象獲取一個對象時,我們需要負責顯示的安排對象的銷燬,其他方法獲取的 的對象將交給自動釋放池進行釋放(單例模式除外) 3:release和drain的區別 當我們向自動釋放池pool發送release消息,將會向池中臨時對象發送一條release消息,並且自身也會唄銷燬。 向它發送drain消息時,只會指定前者。 |
【Objective-C】OC中自動釋放池的基本概念和使用方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
24小時熱門文章