ios - NSSortDescriptor - 基于另一个数组的排序描述符

标签 ios objective-c cocoa-touch core-data nssortdescriptor

我有一个核心数据应用程序。我想获取一种对象,UserUser 具有属性 userId

我有另一个包含 userId 的数组,[1, 4, 3, 5]。我想创建一个 NSSortDescriptor,它根据数组中 userId 的顺序对我的 User 对象进行排序。

这可能吗,我应该怎么做?

更新

我现在已经尝试了以下方法。

  1. 我向我的用户对象添加了一个可转换属性,我在其中存储用户 ID 数组。

  2. 我尝试了以下排序描述符:

    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"userId" ascending:YES     comparator:^NSComparisonResult(id obj1, id obj2) {
        NSUInteger idx1 = [self.user.followingIds indexOfObject:[obj1 valueForKey:@"userId"]];
        NSUInteger idx2 = [self.user.followingIds indexOfObject:[obj2 valueForKey:@"userId"]];
        return idx1 - idx2;
    }];
    

我收到以下错误:

Serious application error.  Exception was caught during Core Data change processing.  This  is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification.   [<__NSCFNumber 0xa337400> valueForUndefinedKey:]: this class is not key value coding-compliant  for the key userId. with userInfo {
    NSTargetObjectUserInfoKey = 2502;
    NSUnknownUserInfoKey = userId;
}
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason:    '[<__NSCFNumber 0xa337400> valueForUndefinedKey:]: this class is not key value coding-   compliant for the key userId.'

更新 2

还想在 User 对象之间添加关系 Followers。任何想法应该如何看待这种关系?见附图。那是对的吗?

enter image description here

最佳答案

这不能用排序描述符来完成,您必须在获取结果后应用自定义比较器函数:

NSArray *userIds = ...; // e.g. @[@1, @4, @3, @5]
NSArray *results = ...; // result of fetch request
NSArray *sorted = [results sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSUInteger idx1 = [userIds indexOfObject:[obj1 valueForKey:@"userId"]];
    NSUInteger idx2 = [userIds indexOfObject:[obj2 valueForKey:@"userId"]];
    return idx1 - idx2;
}];

关于ios - NSSortDescriptor - 基于另一个数组的排序描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16517290/

相关文章:

ios - 如何使用 wkwebview 打开 PDF 链接

UINavigationController 和 UISearchBar 之间的 iOS 9 细线

iphone - NSDictionary到包含键和值的NSArray

cocoa-touch - 我什么时候应该使用界面生成器?

objective-c - iOS - 更改 UIPickerView 组件宽度

ios - 如何从数组中删除包含字典的数组对象

ios - 如何在 Swift 的 AppDelegate 中初始化 NSTimer

objective-c - iOS 上的 Objective C 数据缓存

objective-c - RestKit:两个独立的提要,两种不同的对象类型。一个对象管理器?

ios - swift 和 objective c 中的对象引用计数不同