将NSDictionary插入到排序的NSMutableArray中

时间:2014-09-15 09:12:02

标签: objective-c sorting

我想将NSDictionary对象插入到数组中,并使用objectForKey对数组进行排序。

我设法通过插入,重新排序和重新加载数组来做到这一点,这很好,但我想有一个更好的方法,有,我只是不知道如何使用它。

当前代码:

-(NSMutableArray*)sortArray:(NSMutableArray*)theArray {
    return [[theArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"n"
                                                                                                           ascending:YES]]] mutableCopy];
}

返回重新排序的数组。精细。效果很好,但......最有效率吗?

从另一个问题我收集到这是用于查找要插入的索引的方法:

NSUInteger newIndex = [array indexOfObject:newObject
                         inSortedRange:(NSRange){0, [array count]}
                               options:NSBinarySearchingInsertionIndex
                       usingComparator:comparator];

[array insertObject:newObject atIndex:newIndex];

问题是我不知道如何使用比较器方法,如果我想按每个索引的objectForKey排序,那么这甚至是可能的。

任何人都可以举例说明上述方法,当对象的键(上例中的newObject)进行排序时,让我们说:

[newObject objectForKey:@"sortByThis"];

3 个答案:

答案 0 :(得分:0)

这是比较器

的简单示例
- (NSComparisonResult)compareResulst:(CustomObject *)otherObject {
   if(self.name isEqualToString:key)
   {
      return NSOrderedAscending;
   }
   else
   {
       return NSOrderedDescending
   }
}

NSArray *sArray;
sArray = [unsArray sortedArrayUsingSelector:@selector(compareResulst:)];

这将对数组进行排序。它将遍历对象,并根据你的if,它会上下移动对象......

答案 1 :(得分:0)

使用NSSortDescriptor

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sortByThisKey" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

答案 2 :(得分:0)

这是排序

的一个例子
//For make a we're adding 5 random integers into array inform of NSDictionary
//here, we're taking "someKey" to store the integer (converted to string object) into dictionary
NSMutableArray *array = [NSMutableArray array];
for(int i = 1; i<=5; i++) {
    [array addObject:[NSDictionary dictionaryWithObject:[@(arc4random()%10) stringValue] forKey:@"someKey"]];
}

//create a sort descriptor to sort the array
//give the key in dictionary for which you want to perform sort 
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"someKey" ascending:YES];
//we're doing self sort for mutable array, & that's it, you'll have a sorted array.
[array sortUsingDescriptors:@[sort]];

N.B。

1.而不是&#34; someKey&#34;从上面的示例中,您可以设置要对其执行排序的任何键。

2.还有其他一些排序方法,您可以根据自己的要求使用一种方法。

3.在代码中查看@[sort]。它的完整版是[NSArray arrayWithObject:sort];