个NSArray字符串的排序对自定义对象的NSArray进行排序

个NSArray字符串的排序对自定义对象的NSArray进行排序

本文介绍了根据另一个NSArray字符串的排序对自定义对象的NSArray进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 NSArray 对象,我希望对它们进行相同的排序。一个包含 NSString 对象,另一个包含自定义属性对象。这是我的关键NSArray的样子:

I have two NSArray objects that I would like to be sorted the same. One contains NSString objects, the other custom Attribute objects. Here is what my "key" NSArray looks like:

// The master order
NSArray *stringOrder = [NSArray arrayWithObjects:@"12", @"10", @"2", nil];

带有自定义对象的NSArray:

The NSArray with custom objects:

// The array of custom Attribute objects that I want sorted by the stringOrder array
NSMutableArray *items = [[NSMutableArray alloc] init];
Attribute *attribute = nil;

attribute = [[Attribute alloc] init];
attribute.assetID = @"10";
[items addObject:attribute];

attribute = [[Attribute alloc] init];
attribute.assetID = @"12";
[items addObject:attribute];

attribute = [[Attribute alloc] init];
attribute.assetID = @"2";
[items addObject:attribute];

所以,我想做的是使用 stringOrder 数组,用于确定 items 自定义对象数组的排序。
我该怎么做?

So, what I would like to do is use the stringOrder array to determine the sorting of the items array of custom objects.How can I do this?

推荐答案

在此,我直接比较obj1.assetID的索引在stringOrder中,索引为obj2.assetID in stringOrder(使用Objective-C文字为@()转换NSString => NSNumber)

Hereby, I compare directly the index of obj1.assetID in stringOrder with the index of obj2.assetID in stringOrder (using Objective-C literals for @() to transform NSString => NSNumber)

[items sortUsingComparator:^NSComparisonResult(Attribute *obj1, Attribute *obj2) {
    return [@([stringOrder indexOfObject:obj1.assetID]) compare:@([stringOrder indexOfObject:obj2.assetID])]
}];

或没有ObjC文字:

[items sortUsingComparator:^NSComparisonResult(Attribute *obj1, Attribute *obj2) {
    return [[NSNumber numberWithInt:[stringOrder indexOfObject:obj1.assetID]] compare:[NSNumber numberWithInt:[stringOrder indexOfObject:obj2.assetID]]]
}];

这篇关于根据另一个NSArray字符串的排序对自定义对象的NSArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:25