更改nsmutablearray的值而不会导致内存泄漏

时间:2012-01-13 10:09:39

标签: iphone memory-leaks nsmutablearray

我有一个NSMutableArray,其中包含UIImageView个对象,这些对象会添加到滚动视图中。

[self.scrollView addSubview:UIImageView];
[self.array addObject:UIImageView];

我想删除这些对象并在单击按钮后添加新对象。我尝试通过调用数组上的removeAllObjects:来执行此操作,但这会导致崩溃。

for(int i=0;i<[self.array count];i++){
    [[self.array objectAtIndex:i] removeFromSuperview];
}
[self.array removeAllObjects];

1 个答案:

答案 0 :(得分:0)

您好,请按以下代码 -

UIScrollView *scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 300, 400)];
[self.view addSubview:scrollView];

array=[[NSMutableArray alloc]init];

UIImageView *img1=[[UIImageView alloc]initWithFrame:CGRectMake(20, 0, 100, 100)];
UIImageView *img2=[[UIImageView alloc]initWithFrame:CGRectMake(20, 100, 100, 100)];
UIImageView *img3=[[UIImageView alloc]initWithFrame:CGRectMake(20, 200, 100, 100)];

[img1 setImage:[UIImage imageNamed:@"images.png"]];
[img2 setImage:[UIImage imageNamed:@"images.png"]];
[img3 setImage:[UIImage imageNamed:@"images.png"]];

[array addObject:img1];
[array addObject:img2];
[array addObject:img3];

for(int i=0;i<[array count];i++)    
    [scrollView addSubview:[array objectAtIndex:i]];

然后删除所有视图和空数组以下代码on buttonTouchUpInside() -

 for(int i=0;i<[array count];i++){    
    [[array objectAtIndex:i] removeFromSuperview];    
    [array removeObjectAtIndex:i];
}