Sorting NSArray based on other Array with custom classes

前端 未结 1 690
不知归路
不知归路 2021-01-21 10:57

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.



        
1条回答
  •  囚心锁ツ
    2021-01-21 11:35

    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.

    0 讨论(0)
提交回复
热议问题