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:、ドキュメントには次のように記載されています。

返される配列内のファイルの順序は未定義です。

画像パスをキャプションに関連付ける場合は、その関連付けをどこかに保存する必要があります。キャプションをNSStringのNSArrayに保存する場合は、代わりにNSDictionariesのNSArrayに保存することができます。各辞書には、キー@"imagePath"と@"caption"があります。

また、パスを表すNSStringを処理する場合は、ドキュメントの「パスの操作」にリストされている方法を使用する必要があります。(例:stringByAppendingPathComponent:の代わりにstringByAppendingFormat:

于 2013-02-10T23:09:09.670 に答える