0

I want to save the images in NSLibraryDirectory, the code i am using is replacing image, when next image is saved.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,        NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory  stringByAppendingPathComponent:@"images.doc"];
UIImage *image = [arrayImages objectAtIndex:0];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
4

2 回答 2

3
 NSMutableArray *imag = [[NSMutableArray alloc]initWithObjects:[UIImage imageNamed:@"1333681269.jpeg"],[UIImage imageNamed:@"image001-794043.jpeg"],[UIImage imageNamed:@"Circle.png"], nil];

 for(int i=0;i<[imag count];i++)
 {
       NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
       NSString *documentsDirectory = [paths objectAtIndex:0];
       NSString *imageName = [NSString stringWithFormat:@"savedImage%i.png",i];
       NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imageName];
       NSData *imageData = UIImagePNGRepresentation([imag objectAtIndex:i]);
       [imageData writeToFile:savedImagePath atomically:NO];
}
于 2012-10-30T11:59:27.117 回答
2

每次您必须使用尚未使用的不同名称。因此您必须每次更改文件名。

如果您想在应用程序重新启动后继续工作,请将索引值保存到NSUserDefaults

.h 文件

int index;

更改您的代码,如 .m

index = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"NewFolder"];
NSString *dynamicimagename = [[@"/images" stringByAppendingFormat:@"%d",[[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"]] stringByAppendingFormat:@".doc"];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:dynamicimagename];
UIImage *image = [arrayImages objectAtIndex:0];
NSData *imageData = UIImagePNGRepresentation(image);
BOOL isWritten = [imageData writeToFile:savedImagePath atomically:NO];

index++;
[[NSUserDefaults standardUserDefaults] setInteger:index forKey:@"HighScore"];
于 2012-10-30T12:41:13.510 回答