NSSortDescriptor - 基于另一个数组对描述符进行排序

And*_*ers 5 cocoa-touch core-data objective-c nssortdescriptor ios

我有一个核心数据应用程序.我想要获取一种物体,User.User有财产userId.

我有另一个带有userIds的数组[1, 4, 3, 5].我想创建一个根据数组中s 的顺序对NSSortDescriptor我的User对象进行排序userId.

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

更新

我现在尝试了以下内容.

  1. 我在我的User对象中添加了一个可转换属性,在那里我存储了用户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;
    }];
    
    Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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.'
Run Code Online (Sandbox Code Playgroud)

更新2

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

在此输入图像描述

Mar*_*n R 5

使用排序描述符无法完成此操作,您必须在获取结果后应用自定义比较器函数:

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;
}];
Run Code Online (Sandbox Code Playgroud)

  • @Anders:您是否在获取请求中使用了排序描述符?你不能这样做!在获取请求中使用这样的排序描述符是不可能的.您必须先获取结果,然后按照我的答案中的描述对它们进行排序. - 此外,我不知道你为什么使用可变形属性,这将使事情变得更复杂. (2认同)