Does the UIImage Cache image?

2019-01-14 16:07发布

UIImage *img = [[UIImage alloc] initWithContentsOfFile:@"xx.jpg"]
UIImage *img = [UIImage imageNamed:@"xx.jpg"]

In the second type will the image get cached ?
Whereas the in the first type the images doesn't get cached?

4条回答
We Are One
2楼-- · 2019-01-14 16:33

Correct, the second item is cached.

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-14 16:34

@Dan Rosenstark answer in swift..

extension UIImage {

    static func imageNamed(name: String, cache: Bool) -> UIImage? {
        if (cache) {
            return UIImage(named: name)
        }

        // Using NSString for stringByDeletingPathExtension
        let fullName = NSString(string: name)
        let fileName = fullName.stringByDeletingPathExtension
        let ext = fullName.pathExtension
        let resourcePath = NSBundle.mainBundle().pathForResource(fileName, ofType: ext)

        if let path = resourcePath {
            return UIImage(contentsOfFile: path)
        }
        return nil
    }
}
查看更多
混吃等死
4楼-- · 2019-01-14 16:47

Just wanted to leave this here to help deal with the pathnames issue. This is a method that you can put on a UIImage category.

+(UIImage *)imageNamed:(NSString *)name cache:(BOOL)cache {
    if (cache)
        return [UIImage imageNamed:name];
    name = [[NSBundle mainBundle] pathForResource:[name stringByDeletingPathExtension] ofType:[name pathExtension]]; 
    UIImage *retVal = [[UIImage  alloc] initWithContentsOfFile:name];
    return retVal;
}

If you don't have an easy way to switch to cached, you might end up just using `imageNamed. This is a big mistake in most cases. See this great answer for more details (and upvote both question and answer!).

查看更多
劳资没心,怎么记你
5楼-- · 2019-01-14 16:52
  • The -initWithContentsOfFile: creates a new image without caching, it's an ordinary initialization method.

  • The +imageNamed: method uses cache. Here's a documentation from UIImage Reference:

    This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

    UIImage will retain loaded image, keeping it alive until low memory condition will cause the cache to be purged.

Update for Swift: In Swift the UIImage(named: "...") function is the one that caches the image.

查看更多
登录 后发表回答