在两个NSSortDescriptors上排序失败 - iOS

时间:2013-12-05 10:40:34

标签: ios objective-c arrays sorting nssortdescriptor

我有一个数组填充了一个名为Line的Cored Data对象。每条线与VerticePoint实体具有一对一的关系。 VerticePoint实体包含x和y坐标。

我试图通过x和y坐标对这个数组进行排序。

如果我只按x顶点排序,就像这样,它可以工作:

- (NSArray *)sortVerticesBottomLeftOrigin : (NSArray *)verticesPassed {

    NSArray *sortDescriptorsX = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"origin.x" ascending:YES]];

    NSArray *returnedVertices = [verticesPassed sortedArrayUsingDescriptors:sortDescriptorsX];

    return returnedVertices;

}

但是,如果我添加第二个排序描述符以按y排序,则排序会因日志错误而失败:-[__NSArrayI ascending]: unrecognized selector sent to instance 0xca7e0e0

代码:

- (NSArray *)sortVerticesBottomLeftOrigin : (NSArray *)verticesPassed {

    NSArray *sortDescriptorsX = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"origin.x" ascending:YES]];
    NSArray *sortDescriptorsY = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"origin.y" ascending:YES]];

    NSArray * finishedSort = [NSArray arrayWithObjects:sortDescriptorsX, sortDescriptorsY, nil];

    NSArray *returnedVertices = [verticesPassed sortedArrayUsingDescriptors:finishedSort];

    return returnedVertices;

}

任何想法为什么?

1 个答案:

答案 0 :(得分:0)

试试:

- (NSArray *)sortVerticesBottomLeftOrigin : (NSArray *)verticesPassed {
    NSSortDescriptor *sortDescriptorX = [NSSortDescriptor sortDescriptorWithKey:@"origin.x" ascending:YES];
    NSSortDescriptor *sortDescriptorY = [NSSortDescriptor sortDescriptorWithKey:@"origin.y" ascending:YES];

    NSArray * finishedSort = [NSArray arrayWithObjects:sortDescriptorX, sortDescriptorY, nil];

    NSArray *returnedVertices = [verticesPassed sortedArrayUsingDescriptors:finishedSort];

    return returnedVertices;

}

sortedArrayUsingDescriptors:方法需要一组排序描述符。您可以在那里传递一个包含多个描述符的数组。您不必为每个排序描述符添加一个带有一个排序描述符的数组。