I have a class. Lets call this class MyObject
.
MyObject
has a property called item
.
If I create an instance of MyObject
, instanceOfObject.item
is a NSMetadataItem
.
NSMetadataItem
s have an attribute called NSMetadataItemFSNameKey
.
I have an array of MyObjects
and I want to sort that array by the attribute NSMetadataItemFSNameKey
.
I have tried
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:NSMetadataItemFSNameKey
ascending:YES];
[array sortUsingDescriptors:@[sortDescriptor]];
but this obviously crashes because NSMetadataItemFSNameKey
is not a key of array
. Like I said, NSMetadataItemFSNameKey
is an attribute of instanceOfObject.item
.
Is there a way to do this using NSSortDescriptors
?
I'm not sure if this is what you are looking for, but I use this approach to sort an array of custom objects by a specified NSString
property:
//Sort the list alphabetically by propertyName
NSArray* sortedArray;
sortedArray = [startingArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString* first = [(WSCustomObject*)a propertyName];
NSString* second = [(WSCustomObject*)b propertyName];
return [first compare:second];
}];
You just need to make sure you #import
the custom class header where you are making this call. You can also compare other data types using slight modifications to this approach. If you have a specific data type in mind other than NSString let me know what it is and I can help you modify this one (or I probably already have an example of it floating around I can show you).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.