Reputation: 25
Here is my answer:
-(IBAction)sortBySelectedFilter {
...
[self sortWithKey:@"filename" ascending:ascending selector:@selector(compareFileType:)];
...
}
-(void)sortWithKey:(NSString *)name ascending:(BOOL)asc selector:(SEL)sel {
NSSortDescriptor *byKey = [[[NSSortDescriptor alloc] initWithKey:name
ascending:asc
selector:sel] autorelease];
self.fileNames = [NSMutableArray arrayWithArray:[self.fileNames sortedArrayUsingDescriptors:[NSArray arrayWithObject: byKey]]];
...
}
@interface NSString (FileExtension)
- (NSComparisonResult)compareFileType:(NSString *)filename;
@end
#import "NSString+FileExtension.h"
@implementation NSString (FileExtension)
-(NSComparisonResult)compareFileType:(NSString *)filename {
return [[NSString stringWithFormat:@"%@, %@", [self pathExtension], [self stringByDeletingPathExtension]]
compare:
[NSString stringWithFormat:@"%@, %@", [filename pathExtension], [filename stringByDeletingPathExtension]]];
}
@end
Upvotes: 0
Views: 287
Reputation: 61238
You haven't mentioned whether you're using Core Data or SQLite directly. With Core Data, you can use a custom NSManagedObject subclass (remember to set the class in the Managed Object Model). This subclass would have an -(NSString *)extension method that asks self for -valueForKey:@"filename" and returns just the extension of the file name (using NSString's -pathExtension method). Then change your sort key to "extension" and it should work.
Note: If you're using Core Data and the SQLite store type, you won't be able to fetch or otherwise query using this method, since it doesn't really exist as an attribute in your store.
If you're not using Core Data, I assume your object already has its own class, so it should be obvious how to add your -extension method.
Upvotes: 1