[NSData dataWithContentsOfFile]的内存问题 [英] Memory issue with [NSData dataWithContentsOfFile]

查看:112
本文介绍了[NSData dataWithContentsOfFile]的内存问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发需要图像缓存的应用程序.为此,我正在使用JMImageCache库.缓存工作正常.但是它不能释放被占用的内存下一行.

I am developing application which required image caching. For doing this, I am using JMImageCache library. It is work fine for caching. But It can not release memory occupied by following line.

[NSData dataWithContentsOfFile]

这里是用于从磁盘缓存图像的内容代码的功能.

Here, is function which content code for cache image from disk.

- (UIImage *) imageFromDiskForURL:(NSString *)url {
    NSData *data = [NSData dataWithContentsOfFile:cachePathForURL(url) options:0 error:NULL];
    UIImage *i = [[[UIImage alloc] initWithData:data] autorelease];
    data = nil;
    [data release];
    return i;
}

我用仪器检查过它,每次分配2.34 MB.

I have check it with instruments and it alloc 2.34 MB each time.

推荐答案

data = nil;
[data release];

您为什么期望这一切都能奏效?为什么要发布原始数据?您正在将 release 消息发送到 nil ,这是无操作的消息.

Why do you expect this at all to work? Why should this release the original data? You're sending the release message to nil, which is a no-op.

此外,如果您不使用 alloc copy 创建对象,那么它将自动释放.这意味着,如果您再次释放它,它将被过度释放,并且很可能您的应用程序将崩溃.您需要的是:

Furthermore, if you don't create the object using alloc or copy, then it's autoreleased. That means if you release it once more, it will be overreleased and most likely your app is going to crash. What you need is:

一个.将方法调用包装在显式的自动释放池中:

One. Wrap the method call in an explicit autorelease pool:

- (UIImage *)imageFromDiskForURL:(NSString *)url
{
    UIImage *i;
    @autoreleasepool {
        NSData *data = [NSData dataWithContentsOfFile:cachePathForURL(url) options:0 error:NULL];
        i = [[UIImage alloc] initWithData:data];
    }
    return [i autorelease];
}

二,alloc-init或手动释放数据对象:

Two, alloc-init or manually release the data object:

- (UIImage *)imageFromDiskForURL:(NSString *)url
{
    NSData *data = [[NSData alloc] initWithContentsOfFile:cachePathForURL(url) options:0 error:NULL];
    UIImage *i = [[[UIImage alloc] initWithData:data] autorelease];
    [data release];
    return i;
}

这篇关于[NSData dataWithContentsOfFile]的内存问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆