如何按字典中的对象对模型对象进行排序?

问题描述:

我有一个模型对象,从NSObject的所谓的列扩展。列有两个字段,属性和数据。属性是一个NSDictionary,它存储任意的键/值对,而数据是一个数组。如何按字典中的对象对模型对象进行排序?

列进来的数组,我需要排序他们的值,我知道总是会在属性,一个值与关键ordinal_position。

我用下面的代码进行排序,但它总是失败,因为没有“ORDINAL_POSITION”模型中的对象,只有在模型对象的属性:

NSArray *unsortedArray = [resultStore allValues]; 
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"ordinal_position" ascending:YES] autorelease]; 

NSArray *sortedArray = [unsortedArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; 

我怎么能告诉NSSortDescriptor在模型对象的字典中查找属性?

+0

“我从NSObject的延伸的模型对象称为列。列有两个字段,属性和数据。属性是一个NSDictionary,它存储任意的键/值对,而数据是一个数组。“是否有这样的理由?它与Cocoa的导向完全相反。 – 2010-01-06 18:11:48

你应该定义你自己的选择,返回一个NSComparisonResult并执行它:

- (NSComparisonResult)compareByProperty:(Column *)aColumn { 
    id thisValue = [self valueForKey:@"ordinal_position"]; 
    id otherValue = [self valueForKey:@"ordinal_position"]; 

    return [thisValue compare:otherValue]; // Replace to suit your logic 
}

然后使用NSArray的方法sortedArrayUsingSelector:

NSArray *sortedArray = [unsortedArray sortedArrayUsingSelector:@selector(compareByProperty:)];

请注意,您比较的方法必须存在于您的模型对象,而不是放在您要调用此类的类上 - 成语是您将某个给定的模型对象(self)与第一个对象内的另一个模型对象(aColumn)进行比较。

使用的keyPath:

@ “myDictionary.ordinal_position”