NSmutableArray的问题

时间:2011-02-09 08:24:27

标签: memory-leaks uiview memory-management nsmutablearray

    - (void)createTileOnScreen:(CGRect)rect
    {
    myArray = [[NSMutableArray alloc] init];
    CGRect bounds = rect;
    CGRect myRect = CGRectMake(bounds.origin.x,bounds.origin.y, 
            (int)(bounds.size.width / 11), 
            (int)(bounds.size.height / 10)); 

    for (int i = 0; i < 10; i++) {

        for (int j = 0; j < 11; j++) {
            int index = 10 * i + j;

            Liv *myTile  = [[Liv alloc] initWithFrame:myRect withIndex:index]; 

            float width = (1.0 / 11);
            float height = (1.0 / 10);

                [myTile setImageSection:CGRectMake((j / 11), 
                    (1.0 - ((i+1) / 10)), 
                    width, 
                    height)];
            [self.rotationView addSubview:myTile];
            [myArray addObject:myTile];
            [myTile release];
            myRect.origin.x += myRect.size.width;
        }

        myRect.origin.x = bounds.origin.x;
        myRect.origin.y = myRect.origin.y + myRect.size.height ;



    }
}





    #import "Liv.h"


    @implementation Liv
    @synthesize index;

    - (id)initWithFrame:(CGRect)frame withIndex:(int)index_ {
    if (self = [super initWithFrame:frame]) {
        self.index = index_;
        self.backgroundColor = [UIColor blackColor];
        fadingAnimationDuration = 2.0;
    }
    return self;
    }

    - (id)initWithFrame:(CGRect)frame withIndex:(int)index_ WithColor:(UIColor *)aColor {

    if (self = [self initWithFrame:frame withIndex:index_]) {
        self.backgroundColor = aColor;

    }
     return self;
    }

当屏幕上的创建图块被调用几次时,我看到分配不断增加。你能告诉我如何解除分配吗? myArray没有任何泄漏,也可以从超级视图中删除它。

2 个答案:

答案 0 :(得分:2)

移动

 myArray = [[NSMutableArray alloc] init];

出于

- (void)createTileOnScreen:(CGRect)rect


[myArray release];

将释放你的瓷砖。但您可能希望在发布之前迭代数组并

 [[myArray objectAtIndex:index] removeFromSuperview];

答案 1 :(得分:0)

myArray是如何定义的?它是一个带有@propoerty和@synthesize对应的实例变量吗?

应该是

self.myArray = [NSMutableArray array];

带有相应的

@property(retain) myArray; 
.h文件中的

。那你就没事了。根据你现在所拥有的,每次

- (void)createTileOnScreen:(CGRect)rect

被调用,myArray持有的旧NSMutableArray在被分配给myArray的新NSMutableArray替换时会泄漏。