【问题标题】:returning UIImage from block从块返回 UIImage
【发布时间】:2012-03-17 10:58:20
【问题描述】:

我有以下代码:

- (UIImage *) getPublisherLogo
{
    //check the cache if the logo already exists
    NSString * imageUrl = [NSString stringWithFormat:@"%@/%@&image_type=icon", self.baseUrl, self.imageUrl_];


        ASIHTTPRequest * imageRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imageUrl]];
        [imageRequest setTimeOutSeconds:30.0];
        [imageRequest setDownloadCache:[ASIDownloadCache sharedCache]];
        [imageRequest setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
        [imageRequest setCachePolicy:ASIAskServerIfModifiedWhenStaleCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy]; 
        [imageRequest setCompletionBlock:^(void){


            UIImage *img = [UIImage imageWithData:[imageRequest responseData] ];
            if (img){
                return img;
            }
        }];

        [imageRequest setFailedBlock:^(void){
            NSLog(@"Error in pulling image for publisher %@", [[imageRequest error] userInfo]);
        }];

        [imageRequest startAsynchronous];
    }
}

问题是返回值/UIImage 是在一个块中返回的。我该如何避免这种情况?

【问题讨论】:

  • 请注意,方法应该只是“publisherLogo”;它不应该有 get 前缀。

标签: iphone objective-c ios ipad asihttprequest


【解决方案1】:

您无法从完成块返回任何内容,因为它已返回 void

您可能需要在期望设置图像的对象上创建一个新方法(如 setLogo:(UIImage *)image),并从完成块中调用该方法。

【讨论】:

  • 如果我在我的类中有一个 UIImage 作为属性并在块返回并最终返回此 UIImage 时设置它,是否相同?
  • 是的。事实上,如果属性被命名为“logo”,那么您可以调用 myObject.logo = img 或 [myObject setLogo:img]。它们都是相同的操作。
【解决方案2】:

你可以将你的 img 指针放在块之外,并声明它 __BLOCK 并将其用作闭包。但是你真的需要问自己你打算用 img 做什么,记住调用是异步进行的。我想你应该在块中再次调用另一个方法并将填充的图像作为参数传递。

【讨论】:

    【解决方案3】:

    为了从 ASIHttpRequest 响应中获取对象,我使用通知。

    例如在调用viewController中

    - (void)viewDidLoad {
        // Subscribe notifications
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onGetPhoto:) name:@"getPhotoNotification" object:nil];
    }
    
    - (void)viewDidUnload {
        [super viewDidUnload];
        // Unsubscribe from notifications
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"getPhotoNotification" object:nil];
    }
    
    - (void)onGetPhoto:(NSNotification *)notification {
        ...
    }
    

    在你的完成块中

     [[NSNotificationCenter defaultCenter] postNotificationName:@"getPhotoNotification" object:self userInfo:userInfo];
    

    在 userInfo 中有你的照片。

    【讨论】:

      猜你喜欢
      • 2015-06-26
      • 2011-05-27
      • 2011-11-18
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多