Вопрос

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top