【发布时间】:2015-10-28 17:31:08
【问题描述】:
我正在开发一个用户可以出售/购买的产品应用程序。此应用程序基于集合视图。集合视图具有集合单元格,其中显示产品图像缩略图。
以下代码从服务器获取产品图像,并等待下载所有图像,然后将它们显示在单元格中。以下代码有效,但用户等待 10-20 秒才能查看所有产品。有没有更好的处理方式?
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^(void) {
[self loadFromURL];
dispatch_async(dispatch_get_main_queue(), ^{
});
});
}
-(void)loadFromURL {
NSURL *url = [NSURL URLWithString:@"http://myURL/productAll.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
pElements= (NSMutableArray *)responseObject;
[collectionView reloadData];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Product" message:[error localizedDescription]delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alertView show];
}];
[operation start];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return pElements.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
ProductCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
cell.backgroundColor=[UIColor whiteColor];
NSString *arrayResult = [[pElements objectAtIndex:indexPath.row] objectForKey:@"image"];
NSData *data = [[NSData alloc] initWithBase64EncodedString:arrayResult options:NSDataBase64DecodingIgnoreUnknownCharacters];
cell.productImage.image = [[UIImage alloc] initWithData:data];
cell.productImage.layer.cornerRadius = 10;
cell.productImage.clipsToBounds = YES;
return cell;
}
【问题讨论】:
-
如果你正在寻找代码审查,你应该在codereview.stackexchange.com询问
-
实际上,我已经修改了我的问题,我正在尝试找出如何减少用户等待在集合视图上查看产品的时间。
-
@rmaddy:这看起来不像是代码审查,而是询问如何优化“不完美”代码的不同意见。
-
@erolyeniaras 这个问题在我发表评论后改变了。
-
@texas Nice quistain
标签: ios objective-c uicollectionview afnetworking