如何在Objective-C中正确控制内存溢出



我试图添加到一个数组的所有像素值的图片。如果图片太大,我的应用程序会失去与资产的连接并崩溃。

我如何检查内存是否增长停止和显示警报,因为我不知道什么是最大的图像大小,它可以做,以防止这种加载图片。

我的代码是:
 -(NSArray*)getRGBAFromImage:(UIImage*)image atx:(int)xp atY:(int)yp
 {
NSMutableArray *resultColor = [NSMutableArray array];
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yp) + xp * bytesPerPixel;
 //EDIT: THIS IS THE LOOP
 for (int i = 0 ; i < count ; ++i)
{
    CGFloat red   = (rawData[byteIndex]     *1) ;
    CGFloat green = (rawData[byteIndex + 1] *1) ;
    CGFloat blue  = (rawData[byteIndex + 2] *1) ;
    CGFloat alpha = (rawData[byteIndex + 3] *1) ;
    byteIndex += bytesPerPixel;
    redTotal = redTotal+red;
    greenTotal = greenTotal + green;
    blueTotal = blueTotal + blue;
    UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    [result addObject:acolor];

}    
NSLog(@"width:%i hight:%i Color:%@",width,height,[color description]);
free(rawData);
return resultColor;
 }

或者我应该将它添加到队列中??

谢谢!

虽然图像相当大(32MB),但数组将更大,因为它是一个对象数组。将有8M UIColor颜色对象。在64位设备中,仅仅指向UIColor对象的指针数组就需要64MB,然后再加上UIColor对象大小的8M倍。

最新更新