これはこの投稿の続きです。NSOperationのブロックに問題があり、アプリケーションがでクラッシュしますcompletionblock
。
問題は保持サイクルだと思います(警告があります:) 、この解決策Capturing self strongly in this block is likely to lead to a retain cycle
を試します(上記のコードを参照)、警告は消えましたが、アプリはまだクラッシュします。
アプリケーションは単純なtableViewです。操作は、渡された画像にいくつかの変更を適用します。
自分でブロックを作成して使用するのはこれが初めてです。基本的な説明をお願いします。
コード:
TableViewController.m:
tableView内: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
ImageManager.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
ImageOperations.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
ImageOperations.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