Reputation: 432
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?
Upvotes: 1
Views: 1198
Reputation: 4254
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]];
Upvotes: 0
Reputation: 2830
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
Upvotes: 1
Reputation: 112873
For a NSMutableArray
just use sortUsingSelector
with the built-in sector compare:
.
Ex:
[myArray sortUsingSelector:@selector(compare:)];
Upvotes: 0