Sort NSMutableArray with custom objects by another NSMutableArray
本问题已经有最佳答案,请猛点这里访问。
我有2辆车。第一个数组包含具有
我该怎么做?
1 2 3 4 5 6 7 8 9 10 11 | guideArray = < YOUR SECOND ARRAY WITH STRING OBJECT >; unsortedArray = < YOUR FIRST ARRAY WITH CUSTOM OBJECT >; [unsortedArray sortUsingComparator:^(id o1, id o2) { Items *item1 = o1; Items *item2 = o2; NSInteger idx1 = [guideArray indexOfObject:item1.ItemID]; NSInteger idx2 = [guideArray indexOfObject:item2.ItemID]; return idx1 - idx2; }]; NSLog(@"%@",unsortedArray); |
可以使用以下语法比较两个对象:
1 2 3 4 | [items sortUsingComparator:^NSComparisonResult(Attribute *obj1, Attribute *obj2) { return [[NSNumber numberWithInt:[stringOrder indexOfObject:obj1.itemID]] compare:[NSNumber numberWithInt:[stringOrder indexOfObject:obj2.itemID]]] }]; |
或者您可以使用以下代码段:
1 2 3 4 | NSArray* sortedKeys = [dict keysSortedByValueUsingComparator:^(id obj1, id obj2) { return [obj1 compareTo:obj2]; } |
喜欢编程!
将自定义对象存储在以
1 2 3 4 5 6 7 8 9 10 11 12 | NSArray *objects; // your objects NSMutableArray *hintArray; // your sorted IDs NSMutableDictionary *lookupDict = [[NSMutableDictionary alloc] initWithCapacity:[objects count]]; NSMutableArray *sortedObjects = [[NSMutableArray alloc] initWithCapacity:[hintArray count]]; for (id object in objects) { [lookupDict setValue:object forKey:[object itemID]]; } for (id hint in hintArray) { [sortedObjects addObject:[lookupDict valueForKey:hint]]; } |
编辑:带就地类型
1 2 3 4 5 6 7 8 9 10 11 12 13 | NSMutableArray *objects; NSMutableArray *hintArray; NSMutableDictionary *lookupDict = [[NSMutableDictionary alloc] initWithCapacity:[hintArray count]]; int i = 0; for (NSString *itemID in hintArray) { [lookupDict setValue:[NSNumber numberWithInt:i] forKey:itemID]; i++; } [objects sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { return [[lookupDict valueForKey:[obj1 itemID]] compare:[lookupDict valueForKey:[obj2 itemID]]]; }]; |