我正在尝试使用NSOperation和完成块获取远程Web图像。本质上,接收对象(视图控制器)将调用SGImageManager的fetchImageWithUrlString:completionBlock方法,该方法将依次设置一个具有自己的完成块的SGFetchImageOperation。最后,该操作在完成块内调用完成块。
该应用程序不会崩溃,但会在指示的行上反复中断,并且在检查器中,存在与operationImage和operationUrlString相关联的奇怪值。我不确定如何调试它。我唯一的理论是由于某种原因发生了循环调用。
//SGFetchImageOperation.h
typedef void(^SGFetchImageCompletionBlock)(UIImage *image, NSString *urlString);
@interface SGFetchImageOperation : NSOperation
@property (nonatomic, strong) NSString *urlString;
@property (copy) SGFetchImageCompletionBlock completionBlock;
@end
//SGFetchImageOperation.m
#import "SGFetchImageOperation.h"
@implementation SGFetchImageOperation
- (void)main {
@autoreleasepool {
if (self.isCancelled) {
return;
}
UIImage *image = [self image];
if (self.isCancelled) {
return;
}
if(self.completionBlock && self.urlString && image) {
dispatch_async(dispatch_get_main_queue(), ^{
self.completionBlock(image, self.urlString);
});
}
}
}
- (UIImage *)image{
UIImage *image;
if(self.urlString){
NSURL *url = [NSURL URLWithString:self.urlString];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedAlways error:&error];
if (data) {
image = [UIImage imageWithData:data];
} else {
NSLog(@"Error downloading image. %@", error.localizedDescription);
}
}
return image;
}
@end
//SGImageManager.h
#import "SGFetchImageOperation.h"
@interface SGImageManager : NSObject
- (void)fetchImageWithUrlString:(NSString *)urlString completionBlock:(SGFetchImageCompletionBlock)completionBlock;
@end
//SGImageManager.m
- (void)fetchImageWithUrlString:(NSString *)urlString completionBlock:(SGFetchImageCompletionBlock)completionBlock {
SGFetchImageOperation *operation = [SGFetchImageOperation new];
operation.urlString = urlString;
//Keeps breaking on this line with "Thread x: EXC_BAD_ACCESS (code=2, address=0x1)", but doesn't seem to crash.
operation.completionBlock = ^(UIImage *operationImage, NSString *operationUrlString){
completionBlock(operationImage, operationUrlString);
};
[self.queue addOperation:operation];
}
我认为这里的问题是您要completionBlock
在NSOperation的子类中添加一个名为的属性,该属性已经为定义了方法completionBlock
。
您可以摆脱子类上的属性,而只需使用NSOperation的-setCompletionBlock:
方法。
或者,您可以将当前属性重命名为 SGCompletionBlock
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句