0

对于 URL 列表,我需要使用 ALAssetsLibrary:assetForURL 加载照片,这在一个方法中。众所周知,由于此方法异步工作,但它不会遍历传递的 URL 列表。我发现了这个片段(应该可以):

- (void)loadImages:(NSArray *)imageUrls loadedImages:(NSArray *)loadedImages callback:  (void(^)(NSArray *))callback
{
if (imageUrls == nil || [imageUrls count] == 0) {
    callback(loadedImages);
}
else {
    NSURL *head = [imageUrls head];
    __unsafe_unretained id unretained_self = self;        
    ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
    [library assetForURL:head resultBlock:^(ALAsset *asset) {
        ALAssetRepresentation *assetRepresentation = asset.defaultRepresentation;

        UIImage *image = [UIImage imageWithCGImage:assetRepresentation.fullResolutionImage scale:assetRepresentation.scale orientation:(UIImageOrientation)assetRepresentation.orientation];

        [unretained_self loadImages:[imageUrls tail] loadedImages:[loadedImages arrayByAddingObject:image] callback:callback];
    } failureBlock:^(NSError *error) {
        [unretained_self loadImages:[imageUrls tail] loadedImages:loadedImages callback:callback];
    }];
}
}

如何在表单中编写方法定义(首先是回调)

void loadImages(NSArray *imageUrls, NSArray *loadedImages, ...)  ?

如何从另一种方法(再次主要是回调部分)调用此方法?回调可以在调用方法中还是在此所需的第三种方法中?这个方法需要怎么写?我在这里找到了片段:http: //www.calebmadrigal.com/functional-programming-deal-asynchronicity-objective-c/

4

1 回答 1

1

Use NSThread to call the loadImages method.

NSMutableArray *imageCollection = [NSThread detachNewThreadSelector:@selector (loadImages:)
                         toTarget:self 
                       withObject:imageUrlsCollection];


- (NSMutableArray *)loadImages:(NSArray *)imageUrls 
{
  ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
  NSMutableArray *loadedImages = [[NSMutableArray alloc] init];

  @try
  {
    for(int index = 0; index < [imageUrls count]; index++)
    {
      NSURL *url = [imageUrls objectAtIndex:index];

      [library assetForURL:url resultBlock:^(ALAsset *asset) {

         ALAssetRepresentation *assetRepresentation = asset.defaultRepresentation;

         dispatch_async(dispatch_get_main_queue(), ^{

             UIImage *image = [UIImage imageWithCGImage:assetRepresentation.fullResolutionImage scale:assetRepresentation.scale orientation:(UIImageOrientation)assetRepresentation.orientation];

             [loadedImages addObject:image];

          });

     } failureBlock:^(NSError *error) {

          NSLog(@"Failed to get Image");
     }];

    }
 }
 @catch (NSException *exception)
 {
     NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
 }
 @finally
 {
   return loadedImages;
 }

}

Note: With ARC,take care about invalid attempt to access ALAssetPrivate past the lifetime of its owning ALAssetsLibrary issue

Here is the fix :)

于 2013-03-10T22:58:04.057 回答