![](/img/trans.png)
[英]Sorting array(NSString + Number) using NSSortDescriptor in IOS?
[英]Sorting array of wrapper objects in iOS using NSSortDescriptor
我正在尝试对UserWrapper对象数组进行排序。 包装对象包含对象User,而User对象包含属性UserName(我要根据其排序)。
对用户数组( 源 )进行排序很容易,但是添加的UserWrapper层使我的事情变得复杂。 请帮助!
这是我的代码,适用于简单的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
在您的情况下,排序描述符的key参数也可以通过key path设置 :
[[NSSortDescriptor alloc] initWithKey:@"User.UserName"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)] ;
尽管NSSortDescriptor
的API和文档有点不一致,但是“ key”参数实际上是密钥路径。 因此,您只需指定@"User.UserName"
作为键,您的代码就可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.