当应用程序转到后台状态时,NSCache会删除其所有数据

问题描述 投票:3回答:2

我正在使用NSCache,我正在使用NSCache来存储图像。我在UITableView上展示图像。每当我首先添加图像时,它们会被调整大小,然后添加到表格中,然后添加到NSCache。 eveything工作正常。

但是当我关闭应用程序并再次打开应用程序进入后台时,我的缓存将为空,我的应用程序再次调整图像大小然后显示它,因为一开始我看到一个空表。

我不明白为什么会这样。这是NSCache的预期行为吗? 。如果是,那么我们如何改善用户体验,以便使用不会看到滞后。

这是我的代码,由@ipmcc向我建议

这里的类别是我的实体名称(我使用的是coreData)

// A shared (i.e. global, but scoped to this function) cache
    static NSCache* imageCache = nil;
    // The following initializes the cache once, and only once
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        imageCache = [[NSCache alloc] init];
    });

    // Generate a cache key sufficient to uniquely identify the image we're looking for
    NSString* cacheKey = [NSString stringWithFormat: @"%@", category.name];
    // Try fetching any existing image for that key from the cache.
    UIImage* img = [imageCache objectForKey: cacheKey];
    self.imageView.image = img;

    // If we don't find a pre-existing one, create one
    if (!img)
    {
        // Your original code for creating a resized image...
        UIImage *image1 = [UIImage imageWithData:category.noteImage];

        CGSize newSize;
        if(image1.size.width == 1080 && image1.size.height == 400)
        {
            newSize = CGSizeMake(300, 111);
        }

        dispatch_async(dispatch_get_global_queue(0,0), ^{
            UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
            [image1 drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
            UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

            dispatch_async(dispatch_get_main_queue(), ^{
                // Now add the newly-created image to the cache
                [imageCache setObject: newImage forKey: cacheKey];
                self.imageView.image = newImage;
            });
        });
    }
ios ios7 appdelegate nscache
2个回答
2
投票

是的,它出于某种原因,即使没有内存压力,当应用程序进入后台时,它会立即从缓存中删除数据。要解决此问题,您必须告诉NSCache您的数据不应该被丢弃。

这是你如何解决这个问题。

class ImageCache: NSObject , NSDiscardableContent {

    public var image: UIImage!

    func beginContentAccess() -> Bool {
        return true
    }

    func endContentAccess() {

    }

    func discardContentIfPossible() {

    }

    func isContentDiscarded() -> Bool {
        return false
    }
}

然后像这样在NSCache中使用这个类。

let cache = NSCache<NSString, ImageCache>()

然后像这样在缓存中设置数据

let cacheImage = ImageCache()
cacheImage.image = imageDownloaded
self.cache.setObject(cacheImage, forKey: "somekey" as NSString)

并检索数据

if let cachedVersion = cache.object(forKey: "somekey") {
     youImageView.image = cachedVersion.image
}

0
投票
  1. 是的,这就是NSCache所做的。
  2. 怎么解决?只需使用SDWebImage,超级简单高效。

希望有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.