我的代码花费的时间比预期的要长。如何减少加载时间?以前不需要花这么多时间。我没有更改代码,但速度变慢了。 我的代码流程如下:
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];
}
productList 中有大约 380 条记录。我认为它不应该花费这么多时间。
最佳答案
鉴于该代码中使用 UI*
API 的 futzing 数量,该代码必须在主线程上运行。您正在主线程上加载大量图像,相对而言,图像加载是一个非常缓慢且昂贵的操作。
首先,你真的需要在开始时加载所有 380 图像吗?当它增长到 500 或 1,500 或 15,000 时会发生什么?我敢打赌您的应用程序会在 380 到 15,000 之间的某处耗尽内存....
您的代码应该只加载它需要的图像,然后在该循环之外执行此操作。任何在主线程上运行的东西都会在运行期间阻塞用户交互;保持这些时间段尽可能短(或者,理想情况下,根本不通过将计算移动到后台队列/线程)是理想的。
关于iphone - 代码花费的时间比预期的要长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6059466/