如何将图像名称添加到数组中?

时间:2013-02-17 14:59:39

标签: ios cocoa-touch

在我的应用中,我在内存问题上有一点问题 我的编码技巧还不足以完善 我的代码使用内存四次,我真的需要 我怎样才能改变我的编码?

我的代码是

-(void)viewDidAppear:(BOOL)animated
{ 
UIScrollView * ScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height-88)];// 44(UpperNavigtionBar),-88(Upper+Lower)
ScrollView.pagingEnabled = YES;

// Create a UIImage to hold Info.png
UIImage *image1 = [UIImage imageNamed:@"Image-001.jpg"];
UIImage *image2 = [UIImage imageNamed:@"Image-002.jpg"];
UIImage *image3 = [UIImage imageNamed:@"Image-003.jpg"];
UIImage *image4 = [UIImage imageNamed:@"Image-004.jpg"];
UIImage *image5 = [UIImage imageNamed:@"Image-005.jpg"];
UIImage *image6 = [UIImage imageNamed:@"Image-006.jpg"];
UIImage *image7 = [UIImage imageNamed:@"Image-007.jpg"];
UIImage *image8 = [UIImage imageNamed:@"Image-008.jpg"];
UIImage *image9 = [UIImage imageNamed:@"Image-009.jpg"];
UIImage *image10 = [UIImage imageNamed:@"Image-010.jpg"];
UIImage *image11 = [UIImage imageNamed:@"Image-011.jpg"];
UIImage *image12 = [UIImage imageNamed:@"Image-012.jpg"];
UIImage *image13 = [UIImage imageNamed:@"Image-013.jpg"];

NSArray *images = [[NSArray alloc] initWithObjects:image1,image2,image3,image4,image5,image6,image7,image8,image9,image10,image11,image12,image13,nil];


NSInteger numberOfViews = 13;
for (int i = 0; i < numberOfViews; i++)
{
    CGFloat xOrigin = i * self.view.frame.size.width;

    UIImageView * ImageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height-88)]; // -88(Upper+Lower)
    [ImageView setImage:[images objectAtIndex:i]];

    [ScrollView addSubview:ImageView];
}    
ScrollView.contentSize = CGSizeMake(self.view.frame.size.width*numberOfViews, self.view.frame.size.height-88); // -88(for adding Image View as subview)
[self.view addSubview:ScrollView];
}

1 个答案:

答案 0 :(得分:1)

您可以采取一些措施来限制内存使用量。首先,您应该使用图像的名称填充数组,而不是图像本身。鉴于您的图像的命名方式,您应该能够循环执行此操作。其次,当你加载图像时,使用imageWithContentsOfFile:而不是imageNamed:。后一种方法缓存图像,而前者则不缓存。如果您使用imageNamed:由于缓存,滚动图像(即使是延迟加载)时内存使用量将继续增长 - 在某些时候系统应该清除缓存,这应该可以防止应用程序崩溃,但我不会我认为它会使系统保持关闭设备后台的其他程序。