Iphone 如何从另一个已排序的数组中获取索引数组?
我想按对象对数组进行排序,然后得到如下索引:Iphone 如何从另一个已排序的数组中获取索引数组?,iphone,objective-c,nsarray,Iphone,Objective C,Nsarray,我想按对象对数组进行排序,然后得到如下索引: NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects: @"3", @"2", @"1", @"0", @"1", @"2", nil]; 我希望对象的索引按升序排列。这里,因为最低值的索引是3,所以索引应该是:3,2,4,1,5,0或者类似的东西 有什么想法吗 谢谢 只需对其排序并使用indexOfObject:。像这样: NSArray *sorted = [myAr
NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects: @"3", @"2", @"1", @"0", @"1", @"2", nil];
我希望对象的索引按升序排列。这里,因为最低值的索引是3,所以索引应该是:3,2,4,1,5,0或者类似的东西
有什么想法吗
谢谢 只需对其排序并使用
indexOfObject:
。像这样:
NSArray *sorted = [myArray sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *indices = [NSMutableArray array];
for (id object in myArray)
[indices addObject: [NSNumber numberWithInteger: [sorted indexOfObject: object]]];
(在我的脑海中,希望它能起作用。)您也可以使用下面的代码,希望它对您有用
NSSortDescriptor *_lastDescriptor = [[NSSortDescriptor alloc] initWithKey:@"" ascending:YES];
NSArray *_lastArray = [NSArray arrayWithObject:_lastDescriptor];
firstCharacterArray = (NSMutableArray *)[[nameIndexesDictionary allKeys] sortedArrayUsingDescriptors:_lastArray];
//firstCharacterArray = (NSMutableArray *)[[nameIndexesDictionary allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
for (NSString *eachlastIndex in firstCharacterArray)
{
NSSortDescriptor *lastDescriptor = [[NSSortDescriptor alloc] initWithKey:@""
ascending:YES];
//selector:@selector(localizedCaseInsensitiveCompare:)] ;
NSArray *descriptorslast = [NSArray arrayWithObject:lastDescriptor];
[[nameIndexesDictionary objectForKey:eachlastIndex] sortUsingDescriptors:descriptorslast];
[lastDescriptor release];
}
下面是我最后做的:
//Create a mutable array of the indexes in the myArray (just a list from 0...n)
NSMutableArray *indexes = [[NSMutableArray alloc] init];
for (int i = 0; i < myArray.count; i++){
[indexes addObject: [NSNumber numberWithInteger:i]];
}
//Create a dictionary with myArray as the objects and the indexes as the keys
NSDictionary *tempDictionary = [NSDictionary dictionaryWithObjects:myArray forKeys:indexes];
//Create an array of myArray's keys, in the order they would be in if they were sorted by the values
NSArray *sorted = [tempDictionary keysSortedByValueUsingSelector: @selector(compare:)];
//在myArray中创建一个索引的可变数组(只是0…n中的一个列表)
NSMutableArray*索引=[[NSMutableArray alloc]init];
对于(int i=0;i
太棒了!这几乎奏效了。唯一的问题是,因为有多个对象具有相同的索引,所以它只返回最低的索引值。(参见上面的示例)你知道如何让它返回所有索引值吗?@Jonah:在这种情况下,获取多个索引有一个基本问题,因为示例中的两个对象@“1”和@“1”在逻辑上是相等的,-isEqual:
返回是,几乎可以肯定实际上是同一个对象(因为编译器去掉了重复的常量字符串)。这两个字符串是同一个对象。您将无法区分它们。您可以做的是用占位符替换myArray中的所有对象,如NSNull
。尽管如此,循环会稍微复杂一些。。。