I am trying to sort an array of UserWrapper objects. The wrapper object contains the object User, and the User object contains the property UserName (that I want to sort by).
It us easy enough to sort an array of Users ( source ), but the added layer of UserWrapper complicates things for me. Help please!
Here is my code, which worked for a simple User array:
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"UserName"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)] ;
NSArray *descriptors = [NSArray arrayWithObject:nameDescriptor];
NSMutableArray *contactsStartingWithKey = [nameIndexesDictionary objectForKey:aKey];
[contactsStartingWithKey sortUsingDescriptors:descriptors]; // Exception thrown here because UserName is not a property of UserWrapper, but of UserWrapper.User
The key argument of the sort descriptor can also by a key path , in your case:
[[NSSortDescriptor alloc] initWithKey:@"User.UserName"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)] ;
Although the API and documentation of NSSortDescriptor
are a bit inconsistent, the "key" parameter is actually a key path. So, you can just specify @"User.UserName"
as the key and your code should work.
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.