站在数组上,看怎来使用retain、release
(1)了解NSMutableArray如何实现
(2)进一步深入内存管理
(1)了解NSMutableArray如何实现
NSMutableArray *array = [[NSMutableArray alloc] init];
for(int i=0;i<10;i++)
{
Dog *dog = [[Dog alloc] init];
[dog setID:i];
[array addObject:dog];//里面有用到retain引用,所以dog计数器会变成2
[dog release];//所以这个dog没有释放
}
for(Dog *d in array)
{
NSLog(@"dog is %d",[d ID]);
}
[array release];//将数组中所有的dog 和 array 释放掉
实现数组提供的方法:
(1)(void)addObject:(id)object;
(2)(id) objectAtIndex:(NSUInteger)index;
(3)(void) removeObjectAtIndex:(NSUInteger)index;
(4)(void)removeAll;
(2)进一步深入内存管理
//视频5 main.m
#import <Foundation/Foundation.h>
#import "Dog.h"
int main( int argc, const char * argv[] )
{
@autoreleasepool{
#if0
NSMutableArray * array = [[NSMutableArray alloc] init];
for(int i=0;i<10;i++)
{
Dog *dog = [[Dog alloc] init];
NSLog(@"dog retainCount is %ld\n",[d retainCount]);
[dog setID:i];
[array addObject:dog];//里面有用到retain引用,所以dog计数器会变成2
NSLog(@"dog retainCount is %ld\n",[d retainCount]);
[dog release];//所以这个dog没有释放
}
for(Dog *d in array)
{
NSLog(@"dog is %d",[d ID]);
}
[array release];//将数组中所有的dog 和 array 释放掉
#endif
MyArray * array = [[MyArray alloc] init];
for(int i=0;i<10;i++)
{
Dog *dog = [[Dog alloc] init];
NSLog(@"dog retainCount is %ld\n",[d retainCount]);
[dog setID:i];
[array addObject:dog];//里面有用到retain引用,所以dog计数器会变成2
NSLog(@"dog retainCount is %ld\n",[d retainCount]);
[dog release];//所以这个dog没有释放
}
[array release];
}
return 0;
}
//Dog.h
#import <>
@interface Dog : NSObject
{
int _ID;
}
@property (assign) int ID;
@end
//Dog.m
#import "Dog.h"
@implementation Dog
@synthesize ID=_ID
-(void) dealloc
{
NSLog(@"dog is %d dealloc\n",_ID);
[super dealloc];
}
@end
//MuArray.h
#import <>
@interface MyArray: NSObject
{
NSUInteger _count;
//数组当前有几项元素,是一个整数
id _objs[512];
//创建一个512的数组,有4x512字节
}
@property (assign, readonly) NSUInteger count;
//往MyArray加入一项元素
- (void)addObject:(id)object;
//取得第index项元素
- (id) objectAtIndex:(NSUInteger)index;
//删除第index项元素
- (void) removeObjectAtIndex:(NSUInteger)index;
//删除所有元素
- (void)removeAll;
@end
//MuArray.m
#import "Dog.h"
@implementation Dog
@synthesize count = _count;
- (id) init
{
self = [super init];
if(self)
{
_count = 0;
}
return self;
}
//往MyArray加入一项元素
- (void)addObject:(id)object
{
if(_count >= 512)
return;
_objs[_count] = [object retain];
_count ++;
//这里必须要做[object retain]
}
//取得第index项元素
- (id) objectAtIndex:(NSUInteger)index
{
return _objs[index];
}
//删除第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
{
[self removeAll];
NSLog(@"remove all\n");
[super dealloc];
}
@end