我想通过它的objets对数组进行排序,然后得到如下的索引:
NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects: @"3", @"2", @"1", @"0", @"1", @"2", nil];
我希望对象的索引按升序排列。在这里,因为最低值的索引为3,所以索引将是:3,2,4,1,5,0或类似的东西。
有什么想法吗?
谢谢!
答案 0 :(得分:2)
这是我最终做的事情:
//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:)];
答案 1 :(得分:1)
只需对其进行排序并使用indexOfObject:
即可。像这样:
NSArray *sorted = [myArray sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *indices = [NSMutableArray array];
for (id object in myArray)
[indices addObject: [NSNumber numberWithInteger: [sorted indexOfObject: object]]];
(出于我的想法,希望这有效。)
答案 2 :(得分:1)
您也可以使用下面的代码,可能对您有用,
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];
}