gpt4 book ai didi

objective-c - 对不是基于字符串的字符串的 nsarray 进行排序

转载 作者:可可西里 更新时间:2023-11-01 04:16:44 25 4
gpt4 key购买 nike

所以我有一个数组,我没有按特定顺序从 Web 服务中检索

例子:

0 => x large, 
1 => large,
2 => XX large,
3 => small,
4 => medium,
5 => x small

我需要对它们进行排序:首先基于特定的 - 可以是反向字母:

small
medium
large

其次,我需要根据它们的“x”计数器部分对它们进行排序:

x small
small
medium
large
x large
xx large

我知道我可以通过强力字符串匹配来做到这一点,但我真的很想知道如何巧妙地做到这一点,也许是正则表达式或更优雅的东西?

最佳答案

使用NSComparator block 语法。有点像

NSArray * sizes = [NSArray arrayWithObjects:  @"x small",@"small",@"medium",@"large",@"x large", nil];

NSArray *sortedBySizes =[array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([sizes indexOfObject:[obj1 size]]> [sizes indexOfObject:[obj2 size]])
return (NSComparisonResult)NSOrderedAscending;
if ([sizes indexOfObject:[obj1 size]]< [sizes indexOfObject:[obj2 size]])
return (NSComparisonResult)NSOrderedDescending;
return (NSComparisonResult)NSOrderedSame;
}];

在第二种方法中,我在网络服务器发送的数字和 x 尺寸之间添加了一个映射。现在 [obj size]; 假设返回一个 NSNumber 对象。

NSArray * sizesStrings = [NSArray arrayWithObjects:  @"x small",@"small",
@"medium",@"large",
@"x large",@"xx large",
nil];
NSArray * sizesNumbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:5],
[NSNumber numberWithInt:3],
[NSNumber numberWithInt:4],
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:2],
nil];

NSDictionary *sizes = [NSDictionary dictionaryWithObjects:sizesStrings
forKeys:sizesNumbers];

NSArray *sortedBySizes = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSString *sizeObj1String = [sizes objectForKey:[obj1 size]];
NSString *sizeObj2String = [sizes objectForKey:[obj1 size]];

int i1 = [sizesStrings indexOfObject:sizeObj1String];
int i2 = [sizesStrings indexOfObject:sizeObj2String];

if (i1 > i2)
return (NSComparisonResult)NSOrderedAscending;
if (i2 > i1)
return (NSComparisonResult)NSOrderedDescending;
return (NSComparisonResult)NSOrderedSame;
}];

问题的第二个任务——分组为小、中、大——可以这样完成:

NSDictionary *groups = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSMutableArray array],[NSMutableArray array],[NSMutableArray array], nil] 
forKeys:[NSArray arrayWithObjects:@"small",@"medium",@"large",nil]
];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
int i = [[obj size] intValue];
if (i == 5 || i == 3)
[[groups objectForKey:@"small"] addObject:obj];
else if (i == 2 || i == 0 || i == 1)
[[groups objectForKey:@"large"] addObject:obj];
else
[[groups objectForKey:@"medium"] addObject:obj];

}];

关于objective-c - 对不是基于字符串的字符串的 nsarray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8303523/

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