首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Iphone >

[新手]一个内存有关问题

2013-02-24 
[新手]一个内存问题#import Foundation/Foundation.h@interface GuoA : NSObject@end@implementation Gu

[新手]一个内存问题
#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];
}
@end

int 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试试;

热点排行