.h声明文件
1 // Integer.h 2 // 02-MRC 3 // 4 // Created by ma c on 15/8/13. 5 // Copyright (c) 2015年. All rights reserved. 6 // 7 8 #import9 10 @interface Integer : NSObject11 @property(nonatomic,assign)NSInteger i;12 -(id)initWithI:(NSInteger) i;13 -(void) print;14 +(Integer *)integerWithIntger:(NSInteger) i;15 @end
.m实现文件
1 // Integer.m 2 // 02-MRC 3 // 4 // Created by ma c on 15/8/13. 5 // Copyright (c) 2015年. All rights reserved. 6 // 7 8 #import "Integer.h" 9 10 @implementation Integer11 -(id)initWithI:(NSInteger) i12 {13 self = [super init];14 if(self)15 {16 _i = i;17 }18 return self;19 }20 +(Integer *)integerWithIntger:(NSInteger) i21 {22 return [[Integer alloc]initWithI:i];23 }24 25 -(void) print26 {27 NSLog(@"i = %ld",_i);28 }29 -(void)dealloc30 {31 NSLog(@"integer dealloc");32 [super dealloc];33 }34 @end
主函数测试
1 // main.m 2 // 02-MRC 3 // 4 // Created by ma c on 15/8/13. 5 // Copyright (c) 2015年. All rights reserved. 6 // 7 8 #import9 #import "Integer.h"10 int main(int argc, const char * argv[])11 {12 @autoreleasepool13 {14 //测试手动引用计数15 //1.创建对象会获得对象所有权16 Integer *i1 = [[Integer alloc]initWithI:10];17 NSLog(@"retaincount = %lu",[i1 retainCount]);//118 19 20 //2.只通过指针赋值,不会获得对象所有权21 Integer *i2 = i1;22 NSLog(@"retaincount = %lu",[i2 retainCount]);//123 24 25 //3.通过retain会获得对象的所有权26 [i1 retain];27 NSLog(@"retaincount = %lu",[i1 retainCount]);//228 29 30 //4.将对象添加到容器中,容器中会存储对象的一个引用,会获得对象所有权31 NSMutableArray *array = [NSMutableArray array];32 [array addObject:i1];33 NSLog(@"retaincount = %lu",[i1 retainCount]);//334 35 36 //5.通过release释放对象的所有权37 [i1 release];38 NSLog(@"retaincount = %lu",[i1 retainCount]);//239 40 41 //6.从容器中删除对象,也会释放对象所有权42 [array removeObject:i1];43 NSLog(@"retaincount = %lu",[i1 retainCount]);//144 45 //7.最后再释放一次,对象才会被正常销毁46 [i1 release]; //此时,底层会调用dealloc方法 //047 }48 return 0;49 }
测试结果是:
2015-08-13 17:32:36.408 02-MRC[1599:103515] retaincount = 12015-08-13 17:32:36.409 02-MRC[1599:103515] retaincount = 12015-08-13 17:32:36.410 02-MRC[1599:103515] retaincount = 22015-08-13 17:32:36.410 02-MRC[1599:103515] retaincount = 32015-08-13 17:32:36.410 02-MRC[1599:103515] retaincount = 22015-08-13 17:32:36.410 02-MRC[1599:103515] retaincount = 12015-08-13 17:32:36.410 02-MRC[1599:103515] integer deallocProgram ended with exit code: 0