简体   繁体   English

使用NSSortDescriptor在iOS中对包装对象进行排序

[英]Sorting array of wrapper objects in iOS using NSSortDescriptor

I am trying to sort an array of UserWrapper objects. 我正在尝试对UserWrapper对象数组进行排序。 The wrapper object contains the object User, and the User object contains the property UserName (that I want to sort by). 包装对象包含对象User,而User对象包含属性UserName(我要根据其排序)。

It us easy enough to sort an array of Users ( source ), but the added layer of UserWrapper complicates things for me. 对用户数组( )进行排序很容易,但是添加的UserWrapper层使我的事情变得复杂。 Help please! 请帮助!

Here is my code, which worked for a simple User array: 这是我的代码,适用于简单的User数组:

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: 在您的情况下,排序描述符的key参数也可以通过key path设置

[[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. 尽管NSSortDescriptor的API和文档有点不一致,但是“ key”参数实际上是密钥路径。 So, you can just specify @"User.UserName" as the key and your code should work. 因此,您只需指定@"User.UserName"作为键,您的代码就可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM