我正在尝试使用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];
}
答案 0 :(得分:3)
我认为这里的问题是你将一个名为completionBlock
的属性添加到NSOperation的子类中,该子类已经为completionBlock
定义了方法。
您可以删除子类上的属性,并使用NSOperation的-setCompletionBlock:
方法。
或者,您可以将当前属性重命名为SGCompletionBlock