標籤:
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自動釋放對象記憶體