Two ways to load pictures in the Apple official help document
-
Imagenamed, whose parameters are the name of the picture
-
Imagewithcontentsoffile, whose parameters are the path to the picture file
Here are the main differences:
imagenamed:
Loading pictures In this way is divided into two situations:
-
System cache has this picture
Get directly from the cache
-
System cache does not have this picture
The entire project is traversed through the incoming file name, if the corresponding picture is found, the first thing the IOS system should do is to put the picture in the system cache, in case of the next use of the system cache, then repeat the first step.
So imagine, if you want to load the image of a large number of files, file size, memory shortage, memory leaks, even the program crashes are very easy to happen.
[UIImage Imagenamed:imagename];
Imagewithcontentsoffile and Initwithcontentsoffile
In this way there is only one case where the image data is not cached but only the images are loaded. Therefore, when loading a larger picture, and when the picture is rarely used, these two methods can be used to reduce memory consumption.
NSString *imagefile = [NSString stringwithformat:@ "%@/%@.jpg", [[NSBundle Mainbundle] resourcepath], fileName]; uiimage* image = [UIImage imagewithcontentsoffile:imagefile];
If you want to abbreviate the above code to a single line, you can define a macro in the PCH file that is used throughout the project
#define RESOURCEPATH (path) [[NSBundle Mainbundle] Pathforresource:path Oftype:nil] #define IMAGEWITHPATH (PATH) [ UIImage Imagewithcontentsoffile:path]
So you can get a line of code.
uiimage* image = Imagewithpath (ResourcePath (@ "img.jpg"));
Summarize:
Depending on their strengths and weaknesses to selectively use the appropriate method.
-
It is better to use imagenamed when the picture file is small and used more frequently. For example: UITableViewCell, Uicollectioncell, etc. when loading the same icon, each time the image is used in the table, The picture pointer is only pointed to the same piece of memory. data that can be taken directly from the cache without traversing the entire project. In this case, the efficiency of imagenamed is very high. The same picture object system will only Cache it to memory once, which is very advantageous for the reuse of images.
-
When you load it in the second way, the image is loaded into the program by the system in the form of data. when you don't need to reuse the image, or if you need to store the image as data in a database, or if you want to download a large image over the network, try to load the image using Imagewithdata.
Copyright Notice: This article is for the author Original, welcome reprint share. Please respect the author Labor, reproduced when the statement and the author of the blog link, thank you!
IOS development----imagenamed and Imagewithcontentsoffile differences