0

我知道我在这里犯了一个错误,因为我无法运行我正在尝试构建的项目,而且我在这里尝试做的是从 xml 获取解析的数据,然后将其保存到 nsdata 中,然后将所有这些数据放入缓存,所以当我运行我的项目时,它并不总是加载数据。

@implementation ViewController
{    
    NSCache *myCache;    
}


- (void)viewDidLoad
{    
    myCache = [[NSCache alloc] init];
}

//saving data into cache
NSString *imageURL = [currentData.imageLink];
NSURL *url = [NSURL URLWithString:imageURL];
NSData *data = [NSData dataWithContentsOfURL:url];
data = [imagesCache objectForKey:@"KEY"];
[imagesCache setObject:imageLinks forKey:@"KEY"];
4

2 回答 2

1

一些东西:

  1. 数据下载应该在后台线程上完成。
  2. 最好在缓存中有自己的对象,该对象应该下载图像并缓存图像并将图像保存到磁盘。当缓存被清除时,您应该删除图像,然后在需要时从磁盘重新加载。
  3. 这段代码:

    NSData *data = [NSData dataWithContentsOfURL:url];
    data = [imagesCache objectForKey:@"KEY"];
    [imagesCache setObject:[NSData dataWithContentsOfURL:url] forKey:@"KEY"];
    

Downloads the date, throws it away and replaces it with whatever was in the cache and then updates the cache with something else. It should be more like:

[imagesCache setObject:imageLinks forKey:@"KEY"];

For point 2 your objects should confirm to NSDiscardableContent.

于 2013-08-19T17:48:06.160 回答
-1

NSCache 不将数据保存在磁盘中,只保存在内存中。

如果需要,它可能会自动删除存储在其中的数据。

有关更多信息,请查看此处

于 2013-08-19T16:59:26.377 回答