problem generation Process:
Picture resources in the assets.xcassets , respectively, using the UIImage class method imagenamed and Imagewithcontentsoffile to obtain the picture object, but in strange circumstances, the former gets to the picture object, The latter result is nil. The code is as follows:
1. Through the UIImage class method imagenamed: You can get to the picture object.
@" test.jpg " *img = [UIImage imagenamed:imagename];
2. But through the UIImage class method Imagewithcontentsoffile: Get img 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 uiimage:
- Imagenamed: The created object is cached in system memory and is not immediately released to memory. The advantage is that loading again using this method will reduce the read operation and speed up the program run. Cons: Loading too many pictures takes up a lot of memory space.
-
- Creates a picture object, first looking for the object in the cache, and then fetching the object directly,
- No, the image resource is found from the bundle, and the object is created and returned.
- There are no picture resources in the bundle, then nil is returned.
- Objects created by Imagewithcontentsoffile:magewithcontentsoffile are not cached in system memory. The advantage is that the cache is not generated. Cons: Frequent use of small images, will be frequently read.
Imagenamed only need to pass the filename, Imagewithcontentsoffile needs to pass in the file full path. The full path of the pass file can be Pathforresource:oftype by NSBundle object method: Get. This time to note: Assets.xcassets picture resources can not be NSBundle object method Pathforresource:oftype: obtained. Want to get assets.xcassets picture resources can only be usedimageNamed:。
Workaround:
put the picture resources in a directory outside the Assets.xcassets.
Beginner iOS Encounters problems (ii) UIImage loading pictures encountered problems