【问题标题】:how to manage caching memory in AFNetworking Library如何在 AFNetworking 库中管理缓存内存
【发布时间】:2015-01-15 14:21:21
【问题描述】:

我正在开发一个内容展示应用,其中有一个表格视图和一个与表格中的每一行对应的详细视图。

加载内容的类别有 12 个。

我已经完成了应用程序,它运行良好。现在我需要管理缓存的内存消耗,因为我在运行时收到警告。我正在使用 AFNetowking 库进行缓存。

应用程序运行没有问题。我只需要做一些内存管理并应用代码。

我正在尝试为每个类别分配一些特定的内存和磁盘空间。

以下是我用来为每个类别分配内存和磁盘大小的代码。

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:15 * 512 * 1024
                                                        diskCapacity:10 * 1024 * 1024
                                                            diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];

xcode 版本:6.1
taget ios 版本:6.0
应用:通用

【问题讨论】:

  • 内存警告并不一定意味着它是因为缓存。当应用收到内存警告时,NSURLCache 会清除所有数据。你在设备上测试吗?删除缓存代码时是否看到内存警告?您是否检查过仪器以确定是否存在内存泄漏?

标签: ios caching memory-management afnetworking


【解决方案1】:

我认为建议是不要设置缓存的大小。系统应该会解决这个问题。

我一般会使用一个普通的 NSCache,只根据 URL 存储数据包。然后将数据转换回我所期望的任何图像/xml/文本。

    // This should reference an NSCache instance
    _contentCache = [[NSCache alloc] init];

    // create a key for the request.
    cacheKey = [NSString stringWithFormat:@"%@|%@",uri,body];
    NSData *cacheData = [_contentCache objectForKey:cacheKey];

    // if its in the cache, just return it.
    if (cacheData) {
        return cacheData;
    }

    // Request the data here and return it.

_contentCache 在 AppDelegate 中定义。这样我就可以在整个应用程序中轻松引用它。

    - (id) init {

        _appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        _contentCache = [_appDelegate contentCache];

        return self;
    }

我已将我的课程发布到 GitHub。它不完整,但它可以使用。

postmaster - GitHub

【讨论】:

  • 感谢您的回复,会考虑您建议的解决方案。
  • 您没有答对问题。 NSURLCache 做了所有这些事情以及更多。问题不在于使用哪种缓存机制。对于实现 LRU 或 FIFO 内存缓存的缓存图像等简单的东西,这个解决方案效果最好,但希望缓存在网络库之上。 NSCache 不是为此而设计的。
猜你喜欢
  • 2012-07-11
  • 1970-01-01
  • 2014-03-24
  • 2016-11-23
  • 1970-01-01
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
相关资源
最近更新 更多