我正在使用此代码返回图片:
- (UIImage *)loadThumbnailForImageForUser:(int)userID inFolder:(int)folderNumber withFileName:(NSString *)fileName ofSize:(NSString *)size{
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"IMAGE%@%d", fileName, folderNumber]];
[DropBlocks loadThumbnail:@"" ofSize:@"s" intoPath:filePath completionBlock:^(DBMetadata* metadata, NSError* error){
}];
UIImage *img = [UIImage imageWithContentsOfFile:filePath];
return img;
}
返回的图像总是为零。这是因为稍后会调用completionBlock。反正有没有解决问题并返回图像?
答案 0 :(得分:2)
我通常处理此问题的方法是使用委托模式:
@protocol ImageLoadingProtocol <NSObject>
@required
-(void) imageLoaded:(UIImage*) image;
@end
在图片加载器标题中:
__weak id<ImageLoadingProtocol> delegate;
-(void) initWithDelegate:(id<ImageLoadingProtocol>) delegate;
//or
@property (nonatomic, weak) id<ImageLoadingProtocol> delegate
在您的区块中:
[DropBlocks loadThumbnail:@"" ofSize:@"s" intoPath:filePath completionBlock:^(DBMetadata* metadata, NSError* error){
UIImage *img = [UIImage imageWithContentsOfFile:filePath];
[_delegate imageLoaded:img];
}];
在创建图像加载器的类中:
imageLoader = [[ImageLoader alloc] initWithDelegate:self];
//or
//imageLoader.delegate = self;
然后当块完成后,您的类将收到一条消息imageLoaded:
,您应该实现一个方法来处理它:
-(void) imageLoaded:(UIImage*) image
{
//Here is where your image is usable.
}
这是使用块的另一种解决方案:
- (UIImage *)loadThumbnailForImageForUser:(int)userID inFolder:(int)folderNumber withFileName:
-(NSString *)fileName ofSize:(NSString *)size completionBlock:(void( ^ )( UIImage* image )) completionBlock
{
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"IMAGE%@%d", fileName, folderNumber]];
[DropBlocks loadThumbnail:@"" ofSize:@"s" intoPath:filePath completionBlock:^(DBMetadata* metadata, NSError* error)
{
UIImage *img = [UIImage imageWithContentsOfFile:filePath];
completionBlock(image);
}];
}
警告:注意语法问题和内存管理问题,我没有在IDE中写这个
答案 1 :(得分:0)
不,您不能使用return和异步块。要么在调用之前确保图像可用,或者这是首选选项,请在方法中添加一个完成块并调用它,将图像作为参数提供。然后,您可以在图像已经可用时立即调用该块,或者稍后在内部块可用时调用该块。