Today I wrote a demo involving image caching.
That is, save the image captured by the camera to the application.
It also involves other data, including the image pixel size, key points, and so on...
Therefore, we naturally think of storing the plist file in the. plist file and then writing the plist file into the sandbox.
The first time I wrote it, I directly did this:
NSString *documentsDirectory = [paths objectAtIndex:0]; NSString * namePath = [documentsDirectory stringByAppendingPathComponent:@"gift_info.plist"]; NSMutableArray *myArr = [[NSMutableArray alloc] initWithContentsOfFile:namePath]; NSMutableDictionary *info = [[NSMutableDictionary alloc]init]; [info setObject:myImage forKey:@"img"]; [myArr addObject:info]; [myArr writeToFile:namePath atomically:YES];
Here, myImage is the UIImage data that I want to store.
But what is the result. Obviously, this cannot be stored (that is, the corresponding plist file will not be generated ). Because plist files cannot store UIImage data.
This low-level mistake... it hurts.
Next comes the second version.
[info setObject:UIImagePNGRepresentation(myImage)forKey:@"img"];
The storage type of the image is changed here: to NSData format.
Then, use the following statement when you want to use an image:
UIImage *myImg = [UIImage imageWithData:[myArr objectAtIndex:i]objectForKey:@"img"];
This method works theoretically.
However, converting to data causes the plist file to be too large and slow to load, affecting the display of other data. So it is not a good solution.
The following describes the last method used.
Store the image directly in the sandbox. Then, record the image path in the plist file. Then, you can access the plist file to obtain the image path when using the image.
The following is an example:
I. Store images in sandbox
NSArray * paths = require (NSDocumentDirectory, NSUserDomainMask, YES); NSString * filePath = [[paths objectAtIndex: 0] failed: [NSString stringWithFormat: @ "pic_mongod.png", myI]; // save the file name [UIImagePNGRepresentation (myImage) writeToFile: filePath atomically: YES];
II. Save path in plist
NSMutableDictionary * info = [[NSMutableDictionary alloc] init]; NSArray * paths = Alibaba (NSDocumentDirectory, NSUserDomainMask, YES); NSString * filePath = [[paths objectAtIndex: 0] failed: [NSString stringWithFormat: @ "pic_cmdd.png", conut _]; // Save the object name [info setObject: filePath forKey: @ "img"]; [specialArr addObject: info];
3. Use Images
NSArray * paths = require (NSDocumentDirectory, NSUserDomainMask, YES); NSString * filePath = [[paths objectAtIndex: 0] stringByAppendingPathComponent: [NSString stringWithFormat: @ "pic_mongod.png) current]; // save the file name UIImage * img = [UIImage imageWithContentsOfFile: filePath];