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文件

 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

 

    主函数测试

 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

 

posted @ 2015-08-13 17:54  XYQ全哥  阅读(369)  评论(0编辑  收藏  举报