ios - 使用 NSSortDescriptor 在 iOS 中对包装对象数组进行排序

标签 ios objective-c arrays sorting nssortdescriptor

我正在尝试对 UserWrapper 对象数组进行排序。包装器对象包含对象 User,而 User 对象包含属性 UserName(我想作为排序依据)。

我们很容易对一组用户 (source) 进行排序,但是添加的 UserWrapper 层对我来说使事情变得复杂。请帮忙!

这是我的代码,适用于简单的用户数组:

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

最佳答案

排序描述符的 key 参数也可以是key path,在你的例子中:

[[NSSortDescriptor alloc] initWithKey:@"User.UserName"
                            ascending:YES
                             selector:@selector(localizedCaseInsensitiveCompare:)] ; 

关于ios - 使用 NSSortDescriptor 在 iOS 中对包装对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23350502/

相关文章:

ios - Present ViewController 模态显示奇怪的动画

ios - 如何从Facebook的“个人资料相册”中获取个人资料图片

ios - 即使应用程序打开,通知也会显示在通知栏中

ios - UISwipeGestureRecognizer 在不应该执行的情况下在 if/else 语句中执行

c - gdb 无法打印数组的内容

javascript - 比较两个数组与对象并创建具有不匹配对象的新数组

iphone - 在 Cocos2d 中是否可以为单个对象使用多个标签?

ios - 在 XCode 中使用类似处理的 AWK

ios - iOS 11 中的应用内推广问题

php - 通过 PHP 将 json 对象的列插入新列