0

I have an array of dictionaries as below.

NSMutableArray *newArray
({
    {
        A = John;
        B = THAILAND;
    },
    {
        A = Jack;
        B = US;
    }
    {
        A = Lee;
        B = BRAZIL;
    }
    {
        A = Brandon;
        B = UK;
    }
    {
        A = Jill;
        B = JAPAN;
    }
    {
        A = Johnny;
        B = UK;
    }
    {
        A = Amar;
        B = AUSTRALIA;
    }
})

I want to reorder the above array on the basis of another array (Key B of newArray) which is

NSArray *sortArray = [[NSArray alloc] initWithObjects"US",@"UK",nil];

That means my final array should contain US values first followed by UK followed by the rest. In short, how can I set my own order for an attribute/key in an Array.

How can I do that?

Expected Result :

NSMutableArray *finalArray
({
    {
        A = Jack;
        B = US;
    },
    {
        A = Brandon;
        B = UK;
    }
    {
        A = Johnny;
        B = UK;
    }
    {
        A = John;
        B = THAILAND;
    }
    {
        A = Lee;
        B = BRAZIL;
    }
    {
        A = Jill;
        B = JAPAN;
    }
    {
        A = Amar;
        B = AUSTRALIA;
    }
})

I have tried the below code which gives me ascending order of the key B.

[newArray sortUsingDescriptors:[NSArray arrayWithObjects: [[NSSortDescriptor alloc] initWithKey:@"B" ascending:YES], nil]];
4

2 回答 2

0

您可能必须执行以下操作:

[newArray sortUsingComparator:
    ^NSComparisonResult (id a, id b)
    {
        NSUInteger indexOfA = [sortArray indexOfObject:[a objectForKey:@"B"]];
        NSUinteger indexOfB = ...same thing for b...;

        return [@(indexOfA) compare:@(indexOfB)];
    }];

所以编写你自己的比较器块,使用自定义排序数组给每个对象一个索引,然后比较索引。然后我离开NSNumber返回正确的比较结果,因为它表达了正确的想法,实际上您可能希望跳过隐含的对象创建。

为了完全确定,您可能希望在索引相等时对另一个字段进行排序。

于 2013-06-27T09:42:50.053 回答
0

为了根据既不是升序也不是降序而是随机用户定义顺序的特定键对字典数组进行排序,我使用 NSPredicate 编写了以下代码,我得到了预期的结果。

NSMutableArray *filterArray = [[NSMutableArray alloc] init];
        NSArray *sortArray = [[NSArray alloc] initWithObjects:@"US",@"UK",@"THAILAND",@"BRAZIL",@"JAPAN",@"AUSTRALIA",nil];  // Array containing all the distinct value for the key 'Currency' in self defined order (neither descending nor ascending order).
        NSPredicate *predCurrency = nil;
        // Creating the predicate for individual objects in the sortArray and appending it to the filterArray.
        for (int i = 0; i < [sortArray count]; i++) {
            predCurrency = [NSPredicate predicateWithFormat:@"(NEW_KEY_22 contains[cd] %@)",[sortArray objectAtIndex:i]];
            [filterArray addObjectsFromArray:[myNewArray filteredArrayUsingPredicate:predCurrency]];
        }
        NSLog(@"%@",filterArray);
        // Finally setting the filterArray to the array controller.
        [commercialArrayController  addObjects:filterArray];     // This gives the resultant array having the defined order in sortArray.
于 2013-07-05T12:50:33.550 回答