我尝试修改FGallery(https://github.com/gdavis/FGallery-iPhone).我需要它从相机胶卷读取图像,但我得到内存泄漏.
旧代码(路径是文件位置):
@autoreleasepool {
NSString *path = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] bundlePath],_thumbUrl];
_thumbnail = [UIImage imageWithContentsOfFile:path];
_hasThumbLoaded = YES;
_isThumbLoading = NO;
[self performSelectorOnMainThread:@selector(didLoadThumbnail) withObject:nil waitUntilDone:YES];
}
Run Code Online (Sandbox Code Playgroud)
我的代码(路径是断言库url):
@autoreleasepool {
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) {
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
if (iref) {
_thumbnail = [UIImage imageWithCGImage:iref];
_hasThumbLoaded = YES;
_isThumbLoading = NO;
[self performSelectorOnMainThread:@selector(didLoadThumbnail) withObject:nil waitUntilDone:YES];
}
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror) {
NSLog(@"booya, cant get image - %@",[myerror localizedDescription]);
};
NSURL …Run Code Online (Sandbox Code Playgroud) 当我只在主线程上执行以下操作时iref立即自动释放:
-(void)loadImage:(ALAsset*)asset{
@autoreleasepool {
ALAssetRepresentation* rep = [asset defaultRepresentation];
CGImageRef iref = [rep fullScreenImage];
UIImage* image = [UIImage imageWithCGImage:iref
scale:[rep scale]
orientation:UIImageOrientationUp];
[self.imageView setImage:image];
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我执行imageWithCGImage时:在后台线程上使用GCD iref不会像第一个例子那样立即释放.大约一分钟后:
-(void)loadImage:(ALAsset*)asset{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
@autoreleasepool {
ALAssetRepresentation* rep = [asset defaultRepresentation];
CGImageRef iref = [rep fullScreenImage];
UIImage* image = [UIImage imageWithCGImage:iref
scale:[rep scale]
orientation:UIImageOrientationUp];
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self.imageView setImage:image];
});
}
});
}
Run Code Online (Sandbox Code Playgroud)
如何CGImageRef立即释放对象?
之前的研究:
CGImageRef物体已被分配,并且在它应该被释放后仍然存活了大约一分钟.CGImageRef对象,CGImageRelease我会在图像尝试自动释放一分钟后获得BAD_EXEC异常.iref …