我有一个存储项目的数据库。这些项目可以是不同类型的类型,如文本,视频和图像。加载视图时,我从数据库中获取这些项目,然后在UITableView中显示它们。我面临的问题与在表格视图中显示图像有关。基本上在DB中我存储与图片相关的ALAsset链接,并从中我尝试使用此代码获取其图像:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//...Other Code
else if ([object isMemberOfClass:[Picture class]]){
//Get a reusable cell
cell = [tableView dequeueReusableCellWithIdentifier:@"pictureCellIdentifier"];
// [self performSelectorInBackground:@selector(performAsset:) withObject:dict];
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
if (iref) {
((PictureViewCell *)cell).placeHolderImageView.hidden = YES;
((PictureViewCell *)cell).pictureImageView.image = [UIImage imageWithCGImage:[rep fullResolutionImage] scale:[rep scale] orientation:(UIImageOrientation)[rep orientation]];
}
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
[Utility showAlertViewWithTitle:@"Location Error" message:@"You must activate Location Services to access the photo" cancelButtonTitle:@"Dismiss"];
};
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:[NSURL URLWithString:((Picture *)objectInArray).imagePath]
resultBlock:resultblock
failureBlock:failureblock];
//Set the background for the cell
cell.backgroundView = iv;
}
//...Other code
}
问题在于,当您在单元格中滑动时,方法会被调用,而且应用程序非常慢。所以我想有更好的方法来实现我想要做的事情。我还尝试使用performselectorInBackground:
执行该代码。性能似乎更好但获取图像需要更多时间。
任何帮助都会非常感激。
谢谢!
答案 0 :(得分:0)
这里有一些可以改进的事情。
第一个是你想出来的:在后台线程中加载资产,然后在主线程上准备就绪时将图像添加到单元格中。接下来,您将为您显示的每个单元格创建一个ALAssetsLibrary
对象。理想情况下,应用程序应该只有一个ALAssetsLibrary
对象,只要您需要它就可以保留。首次创建ALAssetsLibrary
,然后重复使用。
- (ALAssetsLibrary *)defaultAssetsLibrary {
if (_library == nil) {
_library = [[ALAssetsLibrary alloc] init];
}
return _library;
}
最后,您在tableview单元格中使用fullResolutionImage
。如果您真的需要显示图片,thumbnailImage
或至少fullScreenImage
应该足够好。
- (void) loadImage:(NSNumber *)indexPath url:(NSURL*)url
{
int index = [indexPath intValue];
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
CGImageRef iref = [[myasset defaultRepresentation] fullScreenImage];
if (iref) {
// TODO: Create a dictionary with UIImage and cell indexPath
// Show the image on main thread
[self performSelectorOnMainThread:@selector(imageReady:) withObject:result waitUntilDone:NO];
}
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
[Utility showAlertViewWithTitle:@"Location Error" message:@"You must activate Location Services to access the photo" cancelButtonTitle:@"Dismiss"];
};
[[self defaultAssetsLibrary] assetForURL:url
resultBlock:resultblock
failureBlock:failureblock];
}
-(void) imageReady:(NSDictionary *) result
{
// Get the cell using index path
// Show the image in the cell
}