Objective-C(8)記憶體管理之自動釋放池

來源:互聯網
上載者:User

標籤:objective-c   ios   xcode   對象   類   物件導向   

  • 自動釋放池

是一種半自動的記憶體管理方式

autorealease方法:

- (instancetype)autorelease

     此方法將對象放到自動釋放池中,當自動釋放池銷毀時,池中的所有對象都會隨之銷毀。

     常見的使用方式:

Person *p = [[[Perosn alloc] init] autorelease];

使用@autoreleasepool關鍵字來使用自動釋放池

     其後的{…}相當於自動釋放池的生存期 ,如:

@autoreleasepool {     Person *p = [[[Perosn alloc] init] autorelease];     …}

好處:不用關心對象釋放的時間、不用關心什麼時候調用release


注意:

1)佔用記憶體較大的對象盡量不要隨意使用autorelease

2) @autoreleasepool可以嵌套

     系統中有一個自動釋放池的棧結構,autorelease方法是將對象放入到棧頂得池子中

3)不要多次調用autorelease,如: 

[[[[Person alloc] init] autorelease] autorelease];

4)自動釋放池銷毀時會對池子中的對象release一次,也就是說autorelease方法並沒有更改引用計數。

將autorelease方法封裝在類對象方法中是一個比較好的做法

+ (AMPerson*) person    {    //return [[[Person alloc] init] autorelease];    return [[[self alloc] init] autorelease];}


舊版本的自動釋放池的使用:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; …[pool release];

自Xcode5之後基本都是使用autorelease


本文出自 “teacherAn” 部落格,請務必保留此出處http://annmeng.blog.51cto.com/3321237/1745625

Objective-C(8)記憶體管理之自動釋放池

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.