Store đối tượng tùy chỉnh trong một cuốn từ điển với itemID
như chìa khóa, sử dụng từ điển này như tra cứu để sắp xếp các đối tượng:
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]];
}
EDIT: Giải pháp với loại inplace của objects
:
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]]];
}];
Nguồn
2013-04-11 08:41:50
mảng ngắn, dựa trên một khóa? –
http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it/805589#805589 –
Tôi đã xem giải pháp này và không phù hợp với câu hỏi –