Sorting of files while reading from document direc

2020-04-29 16:08发布

问题:

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?

回答1:

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



回答2:

Use NSSortDescriptor on your array and enumerate. This is an excellent place to learn in detail on how to go about it.



回答3:

For a NSMutableArray just use sortUsingSelector with the built-in sector compare:. Ex:

[myArray sortUsingSelector:@selector(compare:)];


回答4:

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