Apple official documentation provides two ways to load images into a uiimage object:
1. imagenamed. Its parameter is the image name;
2. imagewithcontentsoffile. Its parameter is also the path of the image file.
So what are the differences between the two types?
Yes. According to Apple's official documentation:
Imagenamed: This method uses a specified name to search in the system cache and returns an image object if it exists. If no image is found in the cache, this method loads the image from the specified document, caches the image, and returns the object. Therefore, imagenamed caches images during loading. Therefore, the imagenamed method is better when images are frequently used. For example, if you need to load the same icon in the tableviewcell of a tableview, It is very efficient to use imagenamed to load images. The system will cache the icon to the memory. Every time you use the image in tableviewcell, the system will only point the image pointer to the same memory. Therefore, imagenamed caches image slices and Stores image data in the memory. The memory of IOS is very precious and will be forcibly released when memory consumption is too large, that is, memory warnings will occur. Releasing the image memory in the IOS system is troublesome and may cause memory leakage. For example, if the animationimages of a uiview object is an nsmutablearray dynamic array containing the uiimage object, and the animation is carried out frame by frame. When imagenamed is used to load images to a dynamic array nsmutablearray, this may cause memory leakage. The reason is obvious.
Imagewithcontentsoffile: only images are loaded, and image data is not cached. Therefore, you can use this method to reduce memory consumption when large images and usage are small.
The following describes the usage of the two methods:
Nsstring * Path = [[nsbundle mainbundle] pathforresource: @ "icon" oftype: @ "PNG"];
Uiimage * image = [uiimage imagewithcontentsoffile: path];
Nsstring * filepath = [[nsbundle mainbundle] pathforresource: Filename oftype: "PNG"];
Nsdata * image = [nsdata datawithcontentsoffile: filepath];
Uiimage * image = [uiimage imagewithdata: Image];
// OR = [uiimage imagewithcontentsoffile: filepath];
The key lies in imagewithcontentsoffile: only images are loaded, and image data is not cached.
Imagenamed: First caches the image to the memory and then displays it.
Differences between two methods for loading Images Using uiimage