Problems with IOS beginners (2) problems with UIImage image loading,
Problem generation process:
Put image resources inAssets. xcassetsIn, the methods imageNamed and imageWithContentsOfFile of the UIImage class are used to obtain the image object. However, in a strange situation, the former gets the image object and the latter returns the nil. The Code is as follows:
1. Use the imageNamed class method of UIImage to obtain the image object.
NSString *imageName = @"test.jpg";UIImage *img = [UIImage imageNamed:imageName];
2. However, by using the class method imageWithContentsOfFile of UIImage: the img is nil.
NSString *imageName = @"test.jpg";NSBundle *bundle = [NSBundle mainBundle];NSString *path = [bundle pathForResource:imageName ofType:nil];UIImage *img = [UIImage imageWithContentsOfFile:path];
Cause analysis:
In fact, there are two ways to create an object for UIImage:
- ImageNamed: The created object is cached in the system memory and not immediately released to the memory. The advantage is that re-loading will reduce read operations and speed up program running. Disadvantage: loading too many images will occupy a large amount of memory space.
- ImageWithContentsOfFile: The objects created by mageWithContentsOfFile are not cached in the system memory. The advantage is that no cache is generated. Disadvantage: small images that are frequently used are frequently read.
ImageNamed only needs to pass in the file name. imageWithContentsOfFile needs to pass in the full path of the file. The full file path can be obtained through the NSBundle object method pathForResource: ofType. Note: The Assets. xcassets image resources cannot be obtained through the NSBundle object method pathForResource: ofType. To obtain Assets. xcassets image resources, you can only useimageNamed:。
Solution:
Place image resources in a directory other than Assets. xcassets.