Problems with IOS beginners (2) problems with UIImage image loading,

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.