3

我正在开发一个进行图像处理并显示结果图像的应用程序。我UIScrollView用来让用户滚动所有图像,因为图像不是标准的 jpg 或 png,加载需要时间。我使用 GCD 异步加载,当完成调度到主队列以显示时。片段如下:

- (void)loadImage:(NSString *)name
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *image = [Reader loadImage:name];
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self displayImage:image];
        });
    });
}

Reader的loadImage方法是这样的:

+ (UIImage *)loadImage:(NSString *)name
{
   UInt8 *data = NULL;
   NSString *mfjPath = [TMP stringByAppendingPathComponent:name];
   NSData *mfjData = [NSData dataWithContentsOfFile:mfjPath];
   if(mfjData){
        data = malloc(sizeof(UInt8)*mfjData.length);
        [mfjData getBytes:data];
   }
   if(data){
        ResultHolder *result = [sDecoder decodeData:data withOffset:0];// static id<IDecoder> sDecoder; in Reader.m before @implementation Reader.
        return [result bitmap];
   }
    retun nil;
}

IDCoder是一个协议,它是

@protocol IDecoder <NSObject>
- (ResultHolder *)decodeData:(UInt8 *) withOffset:(int)offset;
@end

ResultHolder是一个加载简单图像和组合复杂图像的类。如下:

ResultHolder.h

typedef struct color24{
    UInt8 R;
    UInt8 G;
    UInt8 B;
} Color24;

@interface ResultHolder : NSObject
{
    unsigned long mWidth;
    unsigned long mHeight;
    UInt8 *mData;
    CGImageRef mBitmap;

    BOOL isMonoColor;
    Color24 mMonoColor;
}

+ (ResultHolder *)resultHolderWithCGImage:(CGImageRef)image;
+ (ResultHolder *)resultHolderWithData:(UInt8 *)data Width:(unsigned long)width andHeight:(unsigned long)height;
+ (ResultHolder *)resultHolderWithMonoColor:(Color24)monoColor withWidth:(unsigned long)width andHeight:(unsigned long)height;

- (ResultHolder *)initWithData:(UInt8 *)data Width:(unsigned long)width andHeight:(unsigned long) height;
- (ResultHolder *)initWithCGImage:(CGImageRef)image;
- (ResultHolder *)initWithMonoColor:(Color24)monoColor withWidth:(unsigned long)width andHeight:(unsigned long)height;

- (BOOL)isSuccess;
- (UIImage *)bitmap;
- (void)combineFixResultHolder:(ResultHolder *)child Rect:(CGRect)bounds Width:(unsigned long)width andHeight:(unsigned long)height;
- (void)combineResultHolder:(ResultHolder *)child Bounds:(CGRect)bounds Width:(unsigned long)width andHeight:(unsigned long)height;
@end

ResultHolder.m

@implementation ResultHolder

@synthesize width = mWidth;
@synthesize height = mHeight;
@synthesize isMonoColor;
@synthesize monoColor = mMonoColor;

- (ResultHolder *)initWithData:(UInt8 *)data Width:(unsigned long)width andHeight:(unsigned long)height
{

    if (self = [super init]) {        
        mWidth = width;
        mHeight = height;
        mData = malloc(mWidth*mHeight*sizeof(Color24));
        memcpy(mData, data, mWidth*mHeight*sizeof(Color24));

        mBitmap = NULL;
    }

    return self;
}

- (ResultHolder *)initWithCGImage:(CGImageRef)image
{
    if (self = [super init]) {
        mBitmap = CGImageRetain(image);
        mWidth = CGImageGetWidth(image);
        mHeight = CGImageGetHeight(image);
    }
    return self;
}

- (ResultHolder *)initWithMonoColor:(Color24)monoColor withWidth:(unsigned long)width andHeight:(unsigned long)height
{
    if (self = [super init]) {
        mMonoColor = monoColor;

        isMonoColor = YES;
        mWidth = width;
        mHeight = height;
        mBitmap = NULL;
        mData = NULL;
    }

    return self;
}

+ (ResultHolder *)resultHolderWithCGImage:(CGImageRef)image
{
    ResultHolder *resultHolder = [[ResultHolder alloc] initWithCGImage:image];
    return resultHolder;
}

+ (ResultHolder *)resultHolderWithData:(UInt8 *)data Width:(unsigned long)width andHeight:(unsigned long)height
{
    ResultHolder *resultHolder = [[ResultHolder alloc] initWithData:data Width:width andHeight:height];
    return resultHolder;
}

+ (ResultHolder *)resultHolderWithMonoColor:(Color24)monoColor withWidth:(unsigned long)width andHeight:(unsigned long)height
{
    ResultHolder *resultHolder = [[ResultHolder alloc] initWithMonoColor:monoColor withWidth:width andHeight:height];
    return resultHolder;
}

- (BOOL)isSuccess
{
    if ([ReaderConfigures CodecDebug])
        NSLog(@"ResultHolder isSuccess");
    return (mData != NULL || isMonoColor || mBitmap != nil);
}

- (void)fillMonoColor
{

    if (isMonoColor) {
        if (mData) {
            free(mData);
        }
        mData = (UInt8 *)malloc(mWidth*mHeight*sizeof(Color24));

        for (int i = 0; i < mHeight; i++) {
            for (int j = 0; j < mWidth; j++) {
                memcpy(mData+(i*mWidth+j)*3, &mMonoColor, sizeof(Color24));
            }
        }
        isMonoColor = NO;
    }
}


- (void)extractBitmap  
{
    if (mBitmap) {

        CGDataProviderRef dataProvider = CGImageGetDataProvider(mBitmap);
        CFDataRef bitmapData = CGDataProviderCopyData(dataProvider);
        UInt8 * dataSource = (UInt8 *)CFDataGetBytePtr(bitmapData);

        size_t width = CGImageGetWidth(mBitmap);
        size_t height = CGImageGetHeight(mBitmap);
        if(mData)
            free(mData);
        mData = malloc(width*height*3);

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                memcpy(mData+(i*width+j)*3, dataSource+(i*width+j)*4, sizeof(Color24));
            }
        }

        CFRelease(bitmapData);
        CGImageRelease(mBitmap);
        mBitmap = NULL;
    }
}


- (UInt8 *)getRawData
{

    if (mBitmap) {
        [self extractBitmap];
    }
    if (isMonoColor) {
        [self fillMonoColor];
    }

    return mData;
}

- (UIImage *)bitmap
{
    if (mBitmap) {
        UIImage *image = [[UIImage alloc] initWithCGImage:mBitmap];
        CGImageRelease(mBitmap);
        mBitmap = NULL;
        return image; 
    }
    if (isMonoColor) {
        [self fillMonoColor];
    }
    if (mData) {
        CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, mData, mWidth*mHeight*3, NULL);
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGImageRef bitmap = CGImageCreate(mWidth, mHeight, 8, 24, mWidth*3, colorSpace, kCGBitmapByteOrderDefault, dataProvider, NULL, YES, kCGRenderingIntentDefault);
        CGColorSpaceRelease(colorSpace);
        CGDataProviderRelease(dataProvider);
        UIImage *image = [[UIImage alloc] initWithCGImage:bitmap];
        CGImageRelease(bitmap);

        return image;
    }

    return nil;
}

- (void)combineResultHolder:(ResultHolder *) child Bounds:(CGRect) bounds Width:(unsigned long)width andHeight:(unsigned long)height
{
    CGRect rect = CGRectMake(MAX(0, bounds.origin.x), MAX(0, bounds.origin.y),MIN(width - 1, bounds.origin.x + bounds.size.width), MIN(height - 1, bounds.origin.y + bounds.size.height));

    int w = MIN(rect.size.width + 1, child.width);
    int h = MIN(rect.size.height + 1, child.height);

    int dstPos = (height - 1 - (rect.origin.y + h - 1))*width;

    UInt8 *dataParent = [self getRawData];

    if (child.isMonoColor) {
        Color24 childMonoColor = child.monoColor;
        for (int i = 0; i < h; i++) {
            memcpy(dataParent+(dstPos+(int)rect.origin.x)*3, &childMonoColor, w*3);
            dstPos += width;
        }

    } else {
        UInt8 *dataChild = [child getRawData];
        if (dataChild != nil) {
            int srcPos = 0;
            for (int i = 0; i < h; i++) {
                memcpy(dataParent+dstPos*3+((int)rect.origin.x)*3, dataChild+srcPos*3, w*3);
                srcPos += child.width;
                dstPos += width;
            }
        }

    }

}

- (void)combineFixResultHolder:(ResultHolder *)child Rect:(CGRect)bounds Width:(unsigned long)width andHeight:(unsigned long)height
{
    CGRect rect = CGRectMake(bounds.origin.x, height-1-bounds.origin.y-bounds.size.height, bounds.origin.x+bounds.size.width, height-1-bounds.origin.y);

    [self combineResultHolder:child Bounds:rect Width:width andHeight:height];
}

- (void)dealloc
{
    if (mData) {
        free(mData);
        mData = NULL;
    }
    if (mBitmap) {
        CGImageRelease(mBitmap);
        mBitmap = NULL;
    }
}

@end

对于简单的图像,例如仅 JPEG 图像, + (ResultHolder *)resultHolderWithCGImage:(CGImageRef)image;- (UIImage *)bitmap;调用方法。对于一些复杂的, 会ResultHolder提取mBitmapmData,然后结合 sub得到图像。如果我在主线程中加载图像,这些方法效果很好,但是如果我使用 GCD 或在后台加载图像,则很容易崩溃,尤其是在后台加载复杂的图像时。当应用程序崩溃时,主线程状态为 CGSConvertBGR888toRGBA8888 方法错误,其他线程之一正在运行该方法,实际上是. 加载线程和主线程之间似乎存在内存冲突。resultHoldermDataNSThread[ResultHolder dealloc]free(mData)

当应用程序崩溃时,错误是这样的: 在此处输入图像描述

我为这个错误苦苦挣扎了好几天,但仍然找不到解决方法。我希望有人能帮助我。任何建议表示赞赏。

更新:我制作了一个演示项目ReaderDemo来模拟这种情况。有兴趣的可以下载看看错误。这个项目有15张图片,5,7,14张图片会在滚动的时候导致crash,比其他的稍微复杂一些。但是如果您滚动缩略图滚动视图然后单击,它们都可以显示。

4

2 回答 2

3

你有很多问题,但让我们从我发现的第一个开始:

  1. 测试不当

    if (index > [mPageNames count]) {
    

    这需要 >= 否则你会崩溃。

  2. 您正在 mainQueue 上调用 dispatch_sync,这似乎不是一个好的决定(但也许您有一个非常好的决定)-我将其更改为异步,似乎工作正常

  3. 如果您在此项目中启用异常,它将真正帮助您。单击 Xcode 工具栏中的 Break Points 按钮。然后选择 BreakPoints 选项左侧窗格,从右侧数第二个。点击左下角的“+”图标并添加一个 All Exceptions 断点。现在,当您运行调试器时,会在出现问题的地方停止。

  4. 我遇到了最后的崩溃,我会让你修复:

    2012-09-26 08:55:12.378 ReaderDemo[787:11303] MFJAtIndex index out of bounds,index:15,bounds:15
    2012-09-26 08:55:12.379 ReaderDemo[787:11303] *** Assertion failure in -[ImageScrollView showLoadingForMFJ:], /Volumes/Data/Users/dhoerl/Downloads/ReaderDemo/ReaderDemo/ImageScrollView.m:247
    

这应该让你上路。


编辑:您的问题与mData内存管理有关。您正在尝试在代码中管理它的生命周期,但此管理与CGImageDataProvider尝试使用它的管理不同步。崩溃几乎可以肯定(这意味着我 99.99% 确信)是通过在您的类释放了 dealloc 中的内存之后尝试访问数据而CGImageProvided创建的副产品。CGDataProviderCreateWithData我与数据提供商有过类似的经历。

正确的解决方案是删除所有free(data)调用,或者至少删除大部分调用。鉴于您的代码的当前结构,您需要仔细考虑这一点 - 您可能希望用一个标志替换所有测试和 malloc/frees。最后,您要做的是将内存指针交给 ovdr 后CGDataProviderCreateWithData,您需要NULL退出mData并让数据提供者处理删除。

这样做的方法是CGDataProviderCreateWithData在过去的参数中提供一个函数指针:

CGDataProviderReleaseDataCallback
A callback function that releases data you supply to the function CGDataProviderCreateWithData.

typedef void (*CGDataProviderReleaseDataCallback) (
   void *info,
   const void *data,
   size_t size
);

该函数需要做的只是调用free(data);. 因此,只要数据提供者使用完分配的内存,它就会释放它(您无需担心)。

于 2012-09-26T13:01:45.487 回答
-2

如果您想在启用 ARC 的环境中的任何类中释放()或释放您的资源,您必须在“构建阶段”中为您的类设置适当的标志。为此,请在 XCode 中选择您的项目文件,选择您的目标,转到“构建阶段”部分,找到您的类,然后-fno-objc-arc为该类添加标志。或者,也许是另一个原因,您正在调用一些 CoreGraphics 函数,该函数只能在另一个线程中从主线程调用。

于 2012-09-25T10:28:47.737 回答