Objective c 将NSDictionary插入已排序的NSMutableArray
我想将NSDictionary对象插入数组,并按objectForKey对数组进行排序 我通过插入、重新排序和重新加载数组来做到这一点,这很好,但我认为会有更好的方法,我只是不知道如何使用它 当前代码:Objective c 将NSDictionary插入已排序的NSMutableArray,objective-c,sorting,Objective C,Sorting,我想将NSDictionary对象插入数组,并按objectForKey对数组进行排序 我通过插入、重新排序和重新加载数组来做到这一点,这很好,但我认为会有更好的方法,我只是不知道如何使用它 当前代码: -(NSMutableArray*)sortArray:(NSMutableArray*)theArray { return [[theArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescripto
-(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];
问题是我不知道如何使用comparator方法,如果我想按objectForKey对每个索引进行排序,那么这是否可行
当要排序的对象(上例中为newObject)的键为时,有人能举例说明上述方法吗
[newObject objectForKey:@"sortByThis"];
下面是比较器的简单示例
- (NSComparisonResult)compareResulst:(CustomObject *)otherObject {
if(self.name isEqualToString:key)
{
return NSOrderedAscending;
}
else
{
return NSOrderedDescending
}
}
NSArray *sArray;
sArray = [unsArray sortedArrayUsingSelector:@selector(compareResulst:)];
这将对数组进行排序。它将遍历对象,并根据您的if-else将对象上下移动 使用NSSortDescriptor
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sortByThisKey" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
下面是一个排序示例
//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]];
//对于make a,我们将向NSDictionary的数组中添加5个随机整数
//这里,我们使用“someKey”将整数(转换为字符串对象)存储到字典中
NSMutableArray*数组=[NSMutableArray];
对于(int i=1;我对整个数组进行了重新排序,它没有提供在适当索引处插入的能力,这正是我试图实现的。你能详细说明一下吗?也许可以用一个完整的例子。我不明白上面的任何一个怎么可能让我得到正确的索引来插入一个对象?使用字典的键来比较自我d其他对象。并返回NSComparisonResult…让我尝试修改示例。这不只是返回我的排序数组吗?就像我已经在做的一样?我正在尝试获取要插入的indexPath以防止对整个数组重新排序。那么它并不比我当前的方法好。我仍然以这种方式重建整个数组。我想要获取indexPath并以这种方式将对象插入数组,以提高效率。我想在我的情况下,这并不重要。这是我已经在做的事情。我用当前代码更新了我的问题。我正在寻找一种方法来避免使用SortDescriptor,而是获取与数组排序匹配的indexPath。好吗,您可以检查函数可能的执行时间。谢谢,我会看一看。