Objective-C:ARC自動釋放對象內存

ARC是cocoa系統幫你完成對象內存釋放的引用計數機制函數

 

    .h文件測試

 1 //  Person.h
 2 //  01-ARC
 3 //
 4 //  Created by ma c on 15/8/13.
 5 //  Copyright (c) 2015年. All rights reserved.
 6 //
 7 
 8 #import <Foundation/Foundation.h>
 9 
10 @interface Person : NSObject
11 @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文件atom

 1 //  Person.m
 2 //  01-ARC
 3 //
 4 //  Created by ma c on 15/8/13.
 5 //  Copyright (c) 2015年. All rights reserved.
 6 //
 7 
 8 #import "Person.h"
 9 
10 @implementation Person
11 -(id)initWithName:(NSString*) name andAge:(NSInteger) age
12 {
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) age
26 {
27     return [[Person alloc]initWithName:name andAge:age];
28 }
29 
30 -(void)show
31 {
32     NSLog(@"name:%@,age:%ld",_name,_age);
33 }
34 
35 /*
36 建立對象時是先建立父類的部分,再建立子類的部分;
37  銷燬對象時,順序正好相反
38  ARC禁止顯式的發送dealloc消息
39 */
40 -(void)dealloc
41 {
42     NSLog(@"person dealloc");
43     //[super dealloc]; //禁止顯式的發送dealloc消息
44 }
45 @end

 

    主函數測試spa

 1 //  main.m
 2 //  01-ARC
 3 //
 4 //  Created by ma c on 15/8/13.
 5 //  Copyright (c) 2015年. All rights reserved.
 6 //
 7 
 8 #import <Foundation/Foundation.h>
 9 #import "Person.h"
10 int main(int argc, const char * argv[])
11 {
12     @autoreleasepool
13     {
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:22
2015-08-13 17:48:54.905 01-ARC[1636:107161] person dealloc
Program ended with exit code: 0
相關文章
相關標籤/搜索