2

我以这种方式将许多不同的图像保存到文档目录中:

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];

            }


        }
    }

问题是图像的顺序不正确,按照我保存文件的顺序,但它们混淆了。有没有办法订购它们?当我保存到文档目录时,文件是否混淆了?

4

1 回答 1

5

对于contentsOfDirectoryAtPath:error:(这是 的非递归等价物subpathsOfDirectoryAtPath:error:),文档说:

返回数组中文件的顺序未定义。

如果要将图像路径与标题相关联,则应将该关联存储在某处。如果您将字幕存储在 NSStrings 的 NSArray 中,则可以将它们存储在 NSDictionaries 的 NSArray 中。每个字典都有一个键 @"imagePath" 和 @"caption"。

此外,在处理表示路径的 NSString 时,您应该使用文档中使用路径下列出的方法。(例如stringByAppendingPathComponent:,代替stringByAppendingFormat:

于 2013-02-10T23:09:09.670 回答