.h声明文件
// Integer.h
// 02-MRC
//
// Created by ma c on 15/8/13.
// Copyright (c) 2015年. All rights reserved.
// #import <Foundation/Foundation.h> @interface Integer : NSObject
@property(nonatomic,assign)NSInteger i;
-(id)initWithI:(NSInteger) i;
-(void) print;
+(Integer *)integerWithIntger:(NSInteger) i;
@end
.m实现文件
// Integer.m
// 02-MRC
//
// Created by ma c on 15/8/13.
// Copyright (c) 2015年. All rights reserved.
// #import "Integer.h" @implementation Integer
-(id)initWithI:(NSInteger) i
{
self = [super init];
if(self)
{
_i = i;
}
return self;
}
+(Integer *)integerWithIntger:(NSInteger) i
{
return [[Integer alloc]initWithI:i];
} -(void) print
{
NSLog(@"i = %ld",_i);
}
-(void)dealloc
{
NSLog(@"integer dealloc");
[super dealloc];
}
@end
主函数测试
// main.m
// 02-MRC
//
// Created by ma c on 15/8/13.
// Copyright (c) 2015年. All rights reserved.
// #import <Foundation/Foundation.h>
#import "Integer.h"
int main(int argc, const char * argv[])
{
@autoreleasepool
{
//测试手动引用计数
//1.创建对象会获得对象所有权
Integer *i1 = [[Integer alloc]initWithI:];
NSLog(@"retaincount = %lu",[i1 retainCount]);//1 //2.只通过指针赋值,不会获得对象所有权
Integer *i2 = i1;
NSLog(@"retaincount = %lu",[i2 retainCount]);//1 //3.通过retain会获得对象的所有权
[i1 retain];
NSLog(@"retaincount = %lu",[i1 retainCount]);//2 //4.将对象添加到容器中,容器中会存储对象的一个引用,会获得对象所有权
NSMutableArray *array = [NSMutableArray array];
[array addObject:i1];
NSLog(@"retaincount = %lu",[i1 retainCount]);//3 //5.通过release释放对象的所有权
[i1 release];
NSLog(@"retaincount = %lu",[i1 retainCount]);//2 //6.从容器中删除对象,也会释放对象所有权
[array removeObject:i1];
NSLog(@"retaincount = %lu",[i1 retainCount]);//1 //7.最后再释放一次,对象才会被正常销毁
[i1 release]; //此时,底层会调用dealloc方法 //
}
return ;
}
测试结果是:
-- ::36.408 -MRC[:] retaincount =
-- ::36.409 -MRC[:] retaincount =
-- ::36.410 -MRC[:] retaincount =
-- ::36.410 -MRC[:] retaincount =
-- ::36.410 -MRC[:] retaincount =
-- ::36.410 -MRC[:] retaincount =
-- ::36.410 -MRC[:] integer dealloc
Program ended with exit code: