UIImageViewに保存された画像を取得し、その内容を変更して別のUIImageViewの新しい画像にコピーする一連のコードがあります。問題は、プロジェクトを分析するときに、このコードが常にコンパイラからメモリ警告を受け取ることです。このコードをさまざまな方法で実装しようとしましたが、常に別の種類のメモリ警告が表示されます。コンパイラからの出力は、「関数 'CGBitMapContextCreateImage' の呼び出しは +1 の保持カウントを持つコア基盤オブジェクトを返します」と述べており、これによりイメージ オブジェクトの保持カウントが +1 になります。画像オブジェクトを自動解放すると、自動解放が何度も呼び出され、画像オブジェクトの元の保持カウントが 0 であるというメモリ警告がコンパイラに表示されます。
これら 2 つのコンパイラ警告は矛盾していませんか? このコードを修正して、メモリ リークが発生しないようにするにはどうすればよいですか?
-(UIImage *) makeImageLight{
UIImage * image = self.masterImage.image;
NSUInteger width = image.size.width;
NSUInteger height = image.size.height;
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = width * bytesPerPixel;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = height}, image.CGImage);
UInt8* data = (UInt8*)CGBitmapContextGetData(bmContext);
for (size_t i = 0; i < CGBitmapContextGetWidth(bmContext); i++)
{
for (size_t j = 0; j < CGBitmapContextGetHeight(bmContext); j++)
{
int pixel = j * CGBitmapContextGetWidth(bmContext) + i;
pixel = pixel * 4;
UInt8 red = data[pixel + 1]; // If you need this info, enable it
UInt8 green = data[pixel + 2]; // If you need this info, enable it
UInt8 blue = data[pixel + 3]; // If you need this info, enable it
red = ((255 - red) * .3) + red;
green = ((255 - green) * .3) + green;
data[pixel + 1] = red;
data[pixel + 2] = green;
data[pixel + 3] = blue;
}
}
// memory warning occurs in the following line:
image = [UIImage imageWithCGImage:CGBitmapContextCreateImage(bmContext)];
CGContextRelease(bmContext);
return image;
}
気にしないで、コンテキストから作成された CGImage を解放する次のコードを追加して修正しました。
CGImageRef imageRef = CGBitmapContextCreateImage(bmContext);
image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);