Objective-C:ARC自動釋放對象記憶體

來源:互聯網
上載者:User

標籤:

ARC是cocoa系統幫你完成對象記憶體釋放的引用計數機制

 

    .h檔案

 1 //  Person.h 2 //  01-ARC 3 // 4 //  Created by ma c on 15/8/13. 5 //  Copyright (c) 2015年 bjsxt. All rights reserved. 6 // 7  8 #import <Foundation/Foundation.h> 9 10 @interface Person : NSObject11 @property(nonatomic,strong)NSString *name;12 @property(nonatomic,assign)NSInteger age;13 +(Person*)personWithName:(NSString*) name andAge:(NSInteger) age;14 -(id)initWithName:(NSString*) name andAge:(NSInteger) age;15 -(void)show;16 @end

 

    .m檔案

 1 //  Person.m 2 //  01-ARC 3 // 4 //  Created by ma c on 15/8/13. 5 //  Copyright (c) 2015年 bjsxt. All rights reserved. 6 // 7  8 #import "Person.h" 9 10 @implementation Person11 -(id)initWithName:(NSString*) name andAge:(NSInteger) age12 {13     self = [super init];14     if(self)15     {16         _name = name;17         _age = age;18     }19     return self;20 }21 22 /*23  在類方法中,由於沒有建立對象執行個體,所以:self指標不能用,執行個體變數不能用。24  */25 +(Person*)personWithName:(NSString*) name andAge:(NSInteger) age26 {27     return [[Person alloc]initWithName:name andAge:age];28 }29 30 -(void)show31 {32     NSLog(@"name:%@,age:%ld",_name,_age);33 }34 35 /*36 建立對象時是先建立父類的部分,再建立子類的部分;37  銷毀對象時,順序正好相反38  ARC禁止顯式的發送dealloc訊息39 */40 -(void)dealloc41 {42     NSLog(@"person dealloc");43     //[super dealloc]; //禁止顯式的發送dealloc訊息44 }45 @end

 

    主函數測試

 1 //  main.m 2 //  01-ARC 3 // 4 //  Created by ma c on 15/8/13. 5 //  Copyright (c) 2015年 bjsxt. All rights reserved. 6 // 7  8 #import <Foundation/Foundation.h> 9 #import "Person.h"10 int main(int argc, const char * argv[])11 {12     @autoreleasepool13     {14         Person *person = [[Person alloc]initWithName:@"Jim" andAge:22];15         16         [person show];17         //[person dealloc];//error,底層會自動調用該方法用來銷毀對象18     }19     return 0;20 }

 

    測試結果:

2015-08-13 17:48:54.904 01-ARC[1636:107161] name:Jim,age:222015-08-13 17:48:54.905 01-ARC[1636:107161] person deallocProgram ended with exit code: 0

 

Objective-C:ARC自動釋放對象記憶體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.