#import <Foundation/Foundation.h>@interface GuoA : NSObject
@end
@implementation GuoA
- (NSString*) description
{
return (@"I am a GuoA egg");
}
@end
@interface GuoB : NSObject
@end
@implementation GuoB
- (id) init
{
if (self=[super init]) {
NSLog(@"init object GuoB." );
}
return self;
}- (NSString*) description
{
NSString* desc;
desc = [[NSString alloc] initWithFormat:@"I am a GuoB instance."];
return [desc autorelease];
}- (void) dealloc
{
NSLog(@"dealloc object GuoB.");
[super dealloc];
}
@endint main(int argc, const char * argv[])
{ NSAutoreleasePool* pool;
pool = [[NSAutoreleasePool alloc] init];
NSMutableArray* objs;
objs = [NSMutableArray arrayWithCapacity:10];
unsigned int i;
for (i=0; i<10; i++) {
[objs addObject:[ [GuoB alloc] init] ];
}
i=0;
for (GuoB* obj in objs) {
NSString* desc = [obj description];
NSLog(@"%@", desc);
if (i%5==0) {
[pool drain];
}
i++;
}
[pool release];
return 0;
}以上这段代码运行出错,对内存控制的理解还不对,希望大家给指点指点。
@end
@implementation GuoA
- (NSString*) description
{
return (@"I am a GuoA egg");
}
@end
@interface GuoB : NSObject
@end
@implementation GuoB
- (id) init
{
if (self=[super init]) {
NSLog(@"init object GuoB." );
}
return self;
}- (NSString*) description
{
NSString* desc;
desc = [[NSString alloc] initWithFormat:@"I am a GuoB instance."];
return [desc autorelease];
}- (void) dealloc
{
NSLog(@"dealloc object GuoB.");
[super dealloc];
}
@endint main(int argc, const char * argv[])
{ NSAutoreleasePool* pool;
pool = [[NSAutoreleasePool alloc] init];
NSMutableArray* objs;
objs = [NSMutableArray arrayWithCapacity:10];
unsigned int i;
for (i=0; i<10; i++) {
[objs addObject:[ [GuoB alloc] init] ];
}
i=0;
for (GuoB* obj in objs) {
NSString* desc = [obj description];
NSLog(@"%@", desc);
if (i%5==0) {
[pool drain];
}
i++;
}
[pool release];
return 0;
}以上这段代码运行出错,对内存控制的理解还不对,希望大家给指点指点。
NSMutableArray* objs;
objs = [NSMutableArray arrayWithCapacity:10]; 也是autorelease的 [pool drain]的时候会触发垃圾收集你改成 alloc initWithCapacity试试;
还发现放在池外就可以使用 arrayWithCapacity 消息。另外还发现不能使用[pool drain]这个写法。会造成池的重复清空(不知道什么原因!代码逻辑上没看出来是哪出了问题)。
得改用release消息,然后再建造一个新池。