从ios中的照片库中检索照片时内存泄漏

时间:2014-03-30 02:01:17

标签: ios memory uiimage memory-leaks alasset

在我的应用中,我想从照片库中检索照片和视频,然后将它们保存到我的应用文档目录中。     以下是我的代码:

- (UIImage *)getImageFromAsset:(ALAsset *)asset type:(NSInteger)nType
{

    ALAssetRepresentation *assetRepresentation = [asset defaultRepresentation];
    CGImageRef imageReference = [assetRepresentation fullResolutionImage];
    CGFloat imageScale = [assetRepresentation scale];
    UIImageOrientation imageOrientation = (UIImageOrientation)[assetRepresentation orientation];

    UIImage *iImage = [[UIImage alloc] initWithCGImage:imageReference scale:imageScale orientation:imageOrientation];

    return iImage;
}

- (UIImage *)getImageAtIndex:(NSInteger)nIndex type:(NSInteger)nType
{
    return [self getImageFromAsset:(ALAsset *)_assetPhotos[nIndex] type:nType];
}

......

for (NSIndexPath *index in _dSelected) {
    DLog(@"the selected index is %@", index);
    image = nil;
    image = [ASSETHELPER getImageAtIndex:index.row type:ASSET_PHOTO_FULL_RESOLUTION];

    NSString *name = [ASSETHELPER getImageNameAtIndex:index.row];
    NSString *filepath = [files stringByAppendingPathComponent:name];
    NSString *aliapath = [alias stringByAppendingPathComponent:name];
    aliapath = [aliapath stringByAppendingString:THUMBNAIL];
    DLog(@"the files is %@ the alias is %@", filepath, aliapath);

    image = nil;
}

 If I retrieve just 20 or 30 photos, it would be ok, but if I retrieve too many photos(maybe 50 ones), the App will Terminate due to Memory Pressure. I think I have set the image to nil after every one image , so the ios system shoud get back the memory after each for loop. But why Memory leak happens?

1 个答案:

答案 0 :(得分:0)

ARC仍然需要管理你的记忆。只要你处于for循环中,ARC将永远不会释放你的记忆。您需要将循环内部放在自动回收池中。

for (NSIndexPath *index in _dSelected) {
    @autoreleasepool {
        DLog(@"the selected index is %@", index);
        image = nil;
        image = [ASSETHELPER getImageAtIndex:index.row type:ASSET_PHOTO_FULL_RESOLUTION];

        NSString *name = [ASSETHELPER getImageNameAtIndex:index.row];
        NSString *filepath = [files stringByAppendingPathComponent:name];
        NSString *aliapath = [alias stringByAppendingPathComponent:name];
        aliapath = [aliapath stringByAppendingString:THUMBNAIL];
        DLog(@"the files is %@ the alias is %@", filepath, aliapath);

        image = nil;
    }
}

这样可以在处理每张图片时释放你的记忆。