【问题标题】:Sorting array of wrapper objects in iOS using NSSortDescriptor使用 NSSortDescriptor 对 iOS 中的包装对象数组进行排序
【发布时间】:2014-04-28 20:22:05
【问题描述】:

我正在尝试对一组 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

【问题讨论】:

    标签: ios objective-c arrays sorting nssortdescriptor


    【解决方案1】:

    排序描述符的 key 参数也可以通过 key path,在您的情况下:

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

    【讨论】:

      【解决方案2】:

      虽然NSSortDescriptor的API和文档有点不一致,但是“key”参数其实是一个key路径。因此,您只需将 @"User.UserName" 指定为密钥,您的代码就可以工作了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-10
        • 1970-01-01
        • 2012-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-11
        相关资源
        最近更新 更多