程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> [Objective-C]OC中自動釋放池的基本概念和使用方法

[Objective-C]OC中自動釋放池的基本概念和使用方法

編輯:關於C語言

自動釋放池的基本概念

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消息時,只會指定前者。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved