这是这篇文章的延续。我遇到了 NSOperation 块的问题,我的应用程序在completionblock
.
我认为问题是保留周期(我有一个警告:)Capturing self strongly in this block is likely to lead to a retain cycle
,我尝试了这个解决方案(参见上面的代码),警告消失了,但应用程序仍然崩溃。
该应用程序是一个简单的 tableView。该操作在传递的图像中应用了一些修改。
这是我第一次自己创建和使用块,谢谢你给我一些基本的解释
代码:
表视图控制器.m:
在表视图中:cellForRowAtIndexPath:
[[ImageManager sharedManager] modifyImage:[UIImage imageNamed:@"anImage.png"] completionBlock:^(UIImage *image, NSError *error) {
[cell.imageView setImage:image];
}];
ImageManager.h:
#import <Foundation/Foundation.h>
@interface ImageManager : NSObject
@property(nonatomic, strong) NSOperationQueue *imageOperationQueu;
-(void) modifyImage:(UIImage*)image completionBlock:(void(^)(UIImage *image,NSError *error)) completBlock;
+ (id) sharedManager;
@end
图像管理器.m:
#import "ImageManager.h"
#import "ImageOperations.h"
static ImageManager *MySharedManager = nil;
@implementation ImageManager
@synthesize imageOperationQueu;
+ (id)sharedManager
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (MySharedManager == nil) MySharedManager = [[self alloc] init];
});
return MySharedManager;
}
- (NSOperationQueue *)imageOperationQueu
{
if (!imageOperationQueu)
{
imageOperationQueu = [[NSOperationQueue alloc] init];
[imageOperationQueu setMaxConcurrentOperationCount:3];
imageOperationQueu.name = @"imageOperationQueu";
}
return imageOperationQueu;
}
-(void) modifyImage:(UIImage*)image completionBlock:(void(^)(UIImage *image,NSError *error)) completBlock
{
ImageOperations *op = [[ImageOperations alloc]initWithImage:image WithCompletionBlock:completBlock];
[self.imageOperationQueu addOperation:op];
}
@end
图像操作.h:
#import <Foundation/Foundation.h>
typedef void (^CompletionBlock)(UIImage *image,NSError *error);
@interface ImageOperations : NSOperation
@property(nonatomic, weak) CompletionBlock completBlock;
@property(nonatomic, strong) UIImage *imageToTransform;
-(id)initWithImage:(UIImage *)image WithCompletionBlock:(CompletionBlock) block;
@end
图像操作.m:
#import "ImageOperations.h"
@implementation ImageOperations
@synthesize imageToTransform;
@synthesize completBlock;
-(id)initWithImage:(UIImage *)image WithCompletionBlock:(CompletionBlock) block
{
if (self = [super init])
{
NSLog(@"initWithImage");
self.imageToTransform = image;
[self setCompletBlock:block];
}
return self;
}
- (void)main
{
@autoreleasepool
{
UIImage *img = [self setRoundedImage:self.imageToTransform];
__weak ImageOperations *imgOp = self;
[imgOp setCompletionBlock:^{
NSLog(@"setCompletionBlock");
imgOp.completBlock(img,nil);
}];
}
}
-(UIImage*)setRoundedImage:(UIImage*)image
{
// ..
}
@end