Sorting NSArray based on other Array with custom classes

此生再无相见时 提交于 2019-12-20 03:47:49

问题


I desperately need to sort an array: heres the situation,

I need to rearrange / sort and replace arrays based on other an object class from another array.

ParentClass :NSObject{
  NSString *name;
  NSNumber *type;
}

This is the parent class, which fills up the parentArray

parentArray = { parentA, parentB, parentC }

This is another object class, it has ParentClass *parent.

@class ParentClass;

EntryClass: NSObject{
 NSString *name;
 NSNumber *number;
 ParentClass *parent;
}



Now I have an array entryArray = { entryX, entryY, entryZ };

entryX.parent is one of the ParentClasses and all of them are in parentArray.

entryX.parent  == ParentC;
entryY.parent  == ParentA;
entryZ.parent  == ParentB;

I want to sort this entryArray, according the sequence in parentArray. So if ParentArray is:

{
 ParentA,
 ParentB,
 ParentC
}

then I'd want the sorted entryArray to be

{
 entryY,
 entryZ,
 entryX
}

Also, if theres one entry Object is missing, entryZ, then the array should be

{
 entryY,
 @"0.0",
 entryX
}

If tried a number of ways but none really worked, any help is appreciated.

thanks

UPDATE: MORE CLARITy: suppose parentArray is in this sequence

{parentA, parentB}

, and entry array is in

{entryX, entryY}

, I want to rearrange entryArray and if

entryY.parent == parentA, and entryX.parent == parentB

, then based on their postions in parentArray, parentA being the first, i'd want entryY to be before entryX. result = {entryY, entryX}.


回答1:


In fact you have a "sort using selector method" (S.O. source):

- (NSComparisonResult)compareParents:(EntryClass*)otherObject {
    return [parentArray indexOfObject:self.parent] < [parentArray indexOfObject:otherEntry.parent];
}

NSArray *sortedArray;
sortedArray = [entryArray sortedArrayUsingSelector:@selector(compareParents:)];

Doing like this, when sorting entryArray, compareParents is used as a comparison method. That means that e1 will be "less than" e2 iff e1.parent is less than e2.parent. This is exactly what you want.

compareParents should be defines ad method of EntryClass and parentArray should be visible to it.

ORIGINAL ANSWER:

I am not sure I understand fully what you are trying to do; anyway, I would approach the problem using a dictionary where you associate each parent to its entry. That way, once you have your parent array sorted, you can iterate and find out which is the corresponding entry, which will also be (indirectly) sorted.



来源:https://stackoverflow.com/questions/9242715/sorting-nsarray-based-on-other-array-with-custom-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!