I am currently reading the list of files present in my app document directory.
NSString* documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError* error = nil;
NSMutableArray *myArray = (NSMutableArray*)[[[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirectory error:&error]retain];
But before showing the list of files i want to show the all files should be sorted properly.
How can i do this?
Your myArray will be an array of NSStrings. Since they are all in the same directory you can sort it like this:
NSArray * sortedArray =
[myArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
Now it is important to note that contentsOfDirectoryAtPath:documentDirectory error:&error
returns both directories and files. So before getting the sorted array, if you want just files,
NSMutableArray *tempArray=[[NSMutableArray alloc] init];
for(NSString *str in myArray)
{
if([[NSFileManager defaultManager] fileExistsAtPath:str]
[tempArray addObject:str];
}
Now sort this tempArray instead of myArray and you're done
Use NSSortDescriptor on your array and enumerate. This is an excellent place to learn in detail on how to go about it.
For a NSMutableArray
just use sortUsingSelector
with the built-in sector compare:
.
Ex:
[myArray sortUsingSelector:@selector(compare:)];
to sort your Array you can do just.
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES selector:@selector(localizedCompare:)];// for descending sort you can set the parameter ascending to NO.
NSArray* sortedArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];