我以这种方式将许多不同的图像保存到文档目录中:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
int num = arc4random() % 100000000000000;
NSString* path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"%dtest.png", num]];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
然后我这样读取文件:
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//NSString* FinalPath = [documentsDirectory stringByAppendingPathComponent: @"Images/"];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:&error];
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:@"jpg"] || [[strFilePath pathExtension] isEqualToString:@"png"] || [[strFilePath pathExtension] isEqualToString:@"PNG"])
{
NSString *imagePath = [[stringPath stringByAppendingFormat:@"/"] stringByAppendingFormat:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
if(data)
{
@try {
NSString *nameOfGroup = [array objectAtIndex:i];
MWPhoto *photo;
photo= [MWPhoto photoWithFilePath:imagePath];
[finalPhotoArray addObject:photo];
}
@catch (NSException *exception) {
NSString *nameOfGroup = @"No description available for this sheet";
MWPhoto *photo;
photo= [MWPhoto photoWithFilePath:imagePath];
[finalPhotoArray addObject:photo];
}
}
}
问题是图像的顺序不正确,按照我保存文件的顺序,但它们是混淆的。有办法订购吗?当我保存到文档目录时,文件是否混淆了?
最佳答案
对于 contentsOfDirectoryAtPath:error:
(这是 subpathsOfDirectoryAtPath:error:
的非递归等效项),文档说:
The order of the files in the returned array is undefined.
如果您想将图像路径与标题关联起来,您应该将该关联存储在某处。如果您将标题存储在 NSString 的 NSArray 中,则可以将它们存储在 NSDictionaries 的 NSArray 中。每个字典都有一个键@“imagePath”和@“caption”。
此外,在处理表示路径的 NSString 时,您应该使用文档中使用路径下列出的方法。 (例如 stringByAppendingPathComponent:
而不是 stringByAppendingFormat:
)
关于ios - 文档目录对文件进行排序吗? IOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14802144/