好的,所以我正在从服务器下载一堆大图像(5mb),然后将这些碎片拼接在一起并从字节数组中渲染整个图像。但是,我意识到每个图像的数据都没有被释放,因此会导致内存警告和我的应用程序崩溃。我认为由于我的显式 (__bridge_transfer NSData *) 强制转换,ARC 会负责释放对象,但事实证明它仍然是一个问题。在仪器中,大约 1mb 的名为“CGDataProviderCopyData”的对象会堆积起来,并且不会为每个正在拼接到整个图像中的文件丢弃。有什么想法或任何人可以引导我朝着正确的方向前进吗?非常感谢。
// Create array to add all files into total image
NSMutableArray *byteArray = [[NSMutableArray alloc] initWithCapacity:(imageHeight * imageWidth)];
// Iterate through each file in files array
for (NSString *file in array)
{
// Set baseURL for individual file path
NSString *baseURL = [NSString stringWithFormat:@"http://xx.225.xxx.xxx%@",[imageInfo objectForKey:@"BaseURL"]];
// Specify imagePath by appending baseURL to file name
NSString *imagePath = [NSString stringWithFormat:@"%@%@", baseURL, file];
// Change NSString --> NSURL --> NSData
NSURL *imageUrl = [NSURL URLWithString:imagePath];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
// Create image from imageData
UIImage *image = [UIImage imageWithData:imageData];
CGImageRef cgimage = image.CGImage;
size_t width = CGImageGetWidth(cgimage);
size_t height = CGImageGetHeight(cgimage);
size_t bpr = CGImageGetBytesPerRow(cgimage);
size_t bpp = CGImageGetBitsPerPixel(cgimage);
size_t bpc = CGImageGetBitsPerComponent(cgimage);
size_t bytes_per_pixel = bpp / bpc;
// Get CGDataProviderRef from cgimage
CGDataProviderRef provider = CGImageGetDataProvider(cgimage);
// This is the object that is not being released
NSData *data = (__bridge_transfer NSData *)CGDataProviderCopyData(provider); //Using (__bridge_transfer NSData *) casts the provider to type NSData and gives ownership to ARC, but still not discarded
const UInt8 *bytes = (Byte *)[data bytes];
// Log which file is currently being iterated through
NSLog(@"---Stitching png file to total image: %@", file);
// Populate byte array with channel data from each pixel
for(size_t row = 0; row < height; row++)
{
for(size_t col = 0; col < width; col++)
{
const UInt8* pixel =
&bytes[row * bpr + col * bytes_per_pixel];
for(unsigned short i = 0; i < 4; i+=4)
{
__unused unsigned short red = pixel[i]; // red channel - unused
unsigned short green = pixel[i+1]; // green channel
unsigned short blue = pixel[i+2]; // blue channel
__unused unsigned short alpha = pixel[i+3]; // alpha channel - unused
// Create dicom intensity value from intensity = [(g *250) + b]
unsigned short dicomInt = ((green * 256) + blue);
//Convert unsigned short intensity value to NSNumber so can store in array as object
NSNumber *DICOMvalue = [NSNumber numberWithInt:dicomInt];
// Add to image array (total image)
[byteArray addObject:DICOMvalue];
}
}
}
data = nil;
}
return byteArray;
通过 Xcode 运行“分析”也不会显示任何明显的泄漏。