1

我对此有一点问题,我正在从这样的 Url 加载图像:

+ (void)getImageFromURL:(NSString *)imageFilename urlMode:(NSString *)mode block:(id (^)(UIImage *responseImage))aImage {

    NSURL *url = [NSURL URLWithString:[mainURL stringByAppendingString:mode]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];

    AFImageRequestOperation *requestOperation = [AFImageRequestOperation imageRequestOperationWithRequest:request
                                                                              imageProcessingBlock:nil
                                                                                         cacheName:nil
                                                                                           success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) 
                                          {
                                              aImage(image);
                                          }
                                                                                           failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
                                          {
                                              // manage errors
                                          }];
    [[[NSOperationQueue alloc]init] addOperation:requestOperation];
}

我正在尝试将 iVar UIImage *userAvatar 设置为此请求的响应,但问题是,因为它是一个异步请求,所以在我的代码继续之前我没有设置 iVar,所以我的 iVar 是空的m 访问它并将其传递给另一个方法。

4

2 回答 2

2

这就是异步编程的本质!您将不得不重新设计依赖关系,userAvatar以考虑到它的可用性是不确定的。

因此,与其让您的操作的成功块简单地设置userAvatarivar,不如在该图像可用后处理任何需要发生的事情。例如,如果您想设置 aUIImageView的图像,那么在您的成功块中:

dispatch_async(dispatch_get_main_queue(), ^{
    myImageView.image = image;
});

(在不知道你的目标细节和实现细节的情况下,这只是一个“例如……”)

于 2012-03-14T18:52:39.753 回答
1

你忘了[requestOperation start];在最后添加。

于 2012-11-30T21:08:29.043 回答