iOS在UITableView中显示来自ALAsset的图像

我有一个数据库存储项目。 这些项目可以是不同types的文字,video和图像types。 当视图加载时,我从数据库中获取这些项目,并在UITableView中显示它们。 我面临的问题是在表格视图中显示图像。 基本上在数据库我存储的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:执行该代码performselectorInBackground: 。 性能似乎更好,但它需要更多的时间来获取图像。

任何帮助将非常感激。

谢谢!

有几件事情可以在这里改进。

第一个就像你想象的那样:在后台线程中加载资源,然后在主线程上准备就绪的时候将图像添加到单元中。 接下来,您为每个显示的单元创build一个ALAssetsLibrary对象。 理想情况下,只要您需要,应用程序应该只保留一个ALAssetsLibrary对象。 首次创buildALAssetsLibrary ,然后再使用它。

 - (ALAssetsLibrary *)defaultAssetsLibrary { if (_library == nil) { _library = [[ALAssetsLibrary alloc] init]; } return _library; } 

最后,你正在tableview单元格中使用fullResolutionImage 。 如果你真的只需要显示图像,一个thumbnailImage或至lessfullScreenImage应该足够好。

 - (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 }