Reputation: 1117
I am saving many different images to the documents directory in this way:
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];
Then I read the files in this way:
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];
}
}
}
The problem is the images are not ordered correctly, in the order I save the files in, but they are mixed up. Is there a way to order them? when I save to the documents directory, are the files mixed up?
Upvotes: 2
Views: 377
Reputation: 7710
For contentsOfDirectoryAtPath:error:
(which is the non-recursive equivalent of subpathsOfDirectoryAtPath:error:
) the documentation says:
The order of the files in the returned array is undefined.
If you want to associate image paths with captions you should store that association somewhere. If you are storing your captions in an NSArray of NSStrings you could instead store them in an NSArray of NSDictionaries. Each dictionary has a key @"imagePath" and @"caption".
Also, when dealing with NSStrings representing paths you should use the method listed under Working with Paths in the documentation. (e.g. stringByAppendingPathComponent:
instead of stringByAppendingFormat:
)
Upvotes: 5