-1

我有一个NSSet对象。

MyObject集合中的每个对象都是一个具有名为 的属性的实例name

我有另一个NSArray名为 nameIndexes 的名称,其中包含名称值。

我想要一个函数,它接受NSSet并返回一个排序数组,该数组使用 name 属性根据其在 nameIndexes 数组中的位置进行排序。

编辑:

对不起,我的误导,这是一个例子:

我有一组 MyObject(可能顺序不同):

MyObject1 {name:@"A"}

MyObject2 {name:@"B"}

MyObject3 {name:@"C"}

我还有另一个名称数组:

{"B", "A", "C"}

我想要一个 NSArray:

{MyObject2, MyObject1, MyObject3}
4

1 回答 1

6
NSSet *set = //your set.

NSArray *nameIndexes = //the array of names for sorting.

NSArray *result = [[set allObjects] sortedArrayUsingComparator:^NSComparisonResult(MyObject *obj1, MyObject *obj2) {
    int index1 = [nameIndexes indexOfObject:obj1.name];
    int index2 = [nameIndexes indexOfObject:obj2.name];
    return [[NSNumber numberWithInt:index1] compare:[NSNumber numberWithInt:index2]];
}];

Not 100% certain what you are asking but this will sort take the set of names and turn it into a sorted array sorted based on the index of the names in a second array.

After edit

Edit... ok, so your edit completely changed the question. Anyway, from the edit you can just do...

NSArray *result = [[set allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:"name" ascending:YES]]];

This will take the set and return a sorted array sorted by the name property of the objects in alphabetical order.

于 2013-01-04T01:48:04.813 回答