在OC中,使用数组的时候,往往会alloc一个对象后直接就release,这个的原因是在数组里面会调用retain方法来
保持这个对象,所以需要release,基本上使用NSMutableArray对象的都会采用这个方法如下.
NSMutableArray *array = [[NSMutableArray alloc] init];
for(int i = 0; i < 4; i++){
Dog *d = [[Dog alloc] init];
[d setID:i];
NSLog(@"dog reatinCount is %ld",[d retainCount]);
[array addObject:d];
NSLog(@"dog reatinCount is %ld",[d retainCount]);
[d release];
}
[array release];
然后下面我们将自己写一个简单的数组来模拟一下这个数组里面到底进行了什么样的活动,下面代码如下
#import <Foundation/Foundation.h>
@interface MyArray : NSObject
{
NSUInteger _count;//数组当前有几项元素
id _objs[512];//创建了一个512项的数组
}
@property (assign,readonly) NSUInteger count;
- (void) addObject: (id) object;
- (id) objectAtIndex: (NSUInteger) index;
- (void) removeObjectAtIndex : (NSUInteger) index;
- (void) removeAll;
@end
然后是实现文件
#import "MyArray.h"
@implementation MyArray
@synthesize count = _count;
- (id) init
{
self = [super init];
if(self){
_count = 0;
}
return self;
}
- (void) addObject:(id)object
{
if(_count >512)
return;
_objs[_count++] = [object retain];//这里必须retain保证数组里面存放的不是野指针,count++进行下一次存取准备
}
- (id) objectAtIndex:(NSUInteger)index
{
return _objs[index];
}
- (void) removeObjectAtIndex:(NSUInteger)index
{
id obj = _objs[index];
[obj release];//因为上面保存了,所以下面需要释放这个东西
_objs[index] = nil;
}
- (void) removeAll
{
for(int i = 0; i < _count ; i++){
[self removeObjectAtIndex:i];
}
}
- (void) dealloc
{
NSLog(@"数组已经释放");
[self removeAll];
[super dealloc];
}
@end
最后是使用这个文件
MyArray * array = [[MyArray alloc] init];
for(int i = 0; i < 4; i++){
Dog * d = [[ Dog alloc] init];
[d setID:i];
NSLog(@"dog reatinCount is %ld",[d retainCount]);
[array addObject:d];
NSLog(@"dog reatinCount is %ld",[d retainCount]);
[d release];
}
[array release];
}
return 0;
然后最后的运行结果如下
2012-10-14 15:06:15.671 MyArray[1098:303] dog reatinCount is 1
2012-10-14 15:06:15.673 MyArray[1098:303] dog reatinCount is 2
2012-10-14 15:06:15.674 MyArray[1098:303] dog reatinCount is 1
2012-10-14 15:06:15.674 MyArray[1098:303] dog reatinCount is 2
2012-10-14 15:06:15.675 MyArray[1098:303] dog reatinCount is 1
2012-10-14 15:06:15.676 MyArray[1098:303] dog reatinCount is 2
2012-10-14 15:06:15.676 MyArray[1098:303] dog reatinCount is 1
2012-10-14 15:06:15.677 MyArray[1098:303] dog reatinCount is 2
2012-10-14 15:06:15.677 MyArray[1098:303] 数组已经释放
2012-10-14 15:06:15.678 MyArray[1098:303] Dog id 0 dealloc
2012-10-14 15:06:15.678 MyArray[1098:303] Dog id 1 dealloc
2012-10-14 15:06:15.679 MyArray[1098:303] Dog id 2 dealloc
2012-10-14 15:06:15.679 MyArray[1098:303] Dog id 3 dealloc
可以看到,所有的内存都已经释放完毕.