gpt4 book ai didi

objective-c - 根据另一个 NSArray 字符串的排序对自定义对象的 NSArray 进行排序

转载 作者:可可西里 更新时间:2023-11-01 03:24:59 25 4
gpt4 key购买 nike

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

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

带有自定义对象的 NSArray:

// 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 数组的排序。我该怎么做?

最佳答案

在此,我直接比较了 stringOrder 中 obj1.assetID 的索引和 stringOrder 中的 obj2.assetID 的索引(使用 Objective-C 字面量的 @() 来转换 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]]]
}];

关于objective-c - 根据另一个 NSArray 字符串的排序对自定义对象的 NSArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13469667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com