我的代码需要比预期更长的时间。如何减少加载时间?以前没有花这么多时间。我没有更改代码,但它已经放慢了速度。 我的代码流程如下:
for (i =1 ; i< [productList count]; i++) {
UIImage *image;
products *productItem = [productList objectAtIndex:i-1];
if(![productItem.productItemPhoto isEqualToString:@""]){
NSString *productItemPhoto = productItem.productItemPhoto;
NSData* data = [NSData dataWithContentsOfFile:productItemPhoto];
image = [[UIImage alloc] initWithData:data];
}
else{
if(numberOfProductsPerRow == 1)
image = [UIImage imageNamed:@"no-image-2.png"];
else
image = [UIImage imageNamed:@"no-image-1.png"];
}
UIImageView *bg1;
if(numberOfProductsPerRow == 1)
bg1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image-box-s7.png"]];
else
bg1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image-box-s4.png"]];
bg1.frame = CGRectMake(x, y,width, height);
[productScrollView addSubview:bg1];
UIButton *pro1 = [[UIButton alloc] initWithFrame:CGRectMake(x+spacingX, y+spacingY-15, btnWidth, btnHeight)];
[pro1 setImage:image forState:UIControlStateNormal];
[pro1 setTag:i];
[pro1 addTarget:self action:@selector(selectProduct:) forControlEvents:UIControlEventTouchUpInside];
[productScrollView addSubview:pro1 ];
UILabel *lblProductModel = [[UILabel alloc] initWithFrame:CGRectMake(0, height - 40, width, 30)];
lblProductModel.backgroundColor = [UIColor clearColor];
lblProductModel.textAlignment = UITextAlignmentCenter;
lblProductModel.textColor = [UIColor colorWithRed:1.0 green:0.8 blue:0.0 alpha:1];
NSString *price;
if([userSettings.priceToShow isEqualToString:@"WholesalePrice"])
price = [NSString stringWithFormat:@"%@%.0f",productItem.productCurrencySymbol, productItem.productWholesalePrice];
else if([userSettings.priceToShow isEqualToString:@"RetailsalePrice"])
price = [NSString stringWithFormat:@"%@%.0f",productItem.productCurrencySymbol, productItem.productRetailSalesValue];
else
price = @"";
lblProductModel.tag = [productList count] + i;
lblProductModel.text = [NSString stringWithFormat:@"%@ %@", productItem.productModelCode, price];
[bg1 addSubview:lblProductModel];
x = x + width + 10;
if(i%numberOfProductsPerRow == 0){
x = 20;
y=y+height+10;
}
[pro1 release];
[image release];
[bg1 release];
[lblProductModel release];
}
if((i-1)%numberOfProductsPerRow!=0)
scrollViewParent.contentSize = CGSizeMake(0, y+height+spacingY);
else
scrollViewParent.contentSize = CGSizeMake(0, y + spacingY);
productScrollView.contentSize = scrollViewParent.contentSize;
[scrollViewParent addSubview:productScrollView];
}
有大约380条记录进入productList。我认为不应该花这么多时间。
答案 0 :(得分:2)
考虑到该代码中使用UI*
API的数量,该代码必须在主线程上运行。您正在主线程上加载大量图像,图像加载速度非常慢。相对而言,这是一种昂贵的操作。
首先,你真的需要在开始时加载所有380张图片吗?当它增长到500或1,500或15,000时会发生什么?我敢打赌你的应用程序内存耗尽了380到15,000 ......
您的代码应仅加载所需的图像,然后在该循环之外执行此操作。只要它运行,在主线程上运行的任何东西都将阻止用户交互;保持那些时间段尽可能短(或者理想情况下,通过将计算移动到后台队列/线程完全没有)是理想的。