Input Array: (
{
title = "Antonik's BBQ";
},
{
title = "Jigsaw Salon";
},
{
title = "London Fish 'N Chips";
},
{
title = "Kenneth of London";
},
{
title = "Il Pastaio Fresh Pasta Company";
},
{
title = "Everett & Jones Barbeque";
},
{
title = "Duke of Edinburgh";
}
);
从上面的数组中,如果搜索文本是“london”,我需要按如下方式对数组进行修改。
Expected sorted array: (
{
title = "Kenneth of London";
},
{
title = "London Fish 'N Chips";
},
{
title = "Antonik's BBQ";
},
{
title = "Jigsaw Salon";
},
{
title = "Il Pastaio Fresh Pasta Company";
},
{
title = "Everett & Jones Barbeque";
},
{
title = "Duke of Edinburgh";
}
);
我尝试使用谓词如下。
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"title CONTAINS[cd] %@", _yelpSearchBar.text];
inputArray=[inputArray filteredArrayUsingPredicate:predicate];
但它会返回包含“london”的结果。有人可以告诉我正确排序的方法。
感谢。
答案 0 :(得分:1)
我能想象的唯一方法就是手动完成。这已经过测试:
» cat arraysort.m
#import <Foundation/Foundation.h>
NSArray *specialSort(NSArray *array, NSString *searchString)
{
NSMutableArray *matched = [NSMutableArray new];
NSMutableArray *unmatched = [NSMutableArray new];
for (NSString *str in array) {
if ([str rangeOfString:searchString options:NSCaseInsensitiveSearch].location != NSNotFound)
[matched addObject:str];
else
[unmatched addObject:str];
}
return
[[matched sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] arrayByAddingObjectsFromArray:unmatched];
}
int main(int argc, const char **argv) {
@autoreleasepool {
NSArray *arr = @[@"Antonik's BBQ", @"Jigsaw Salon", @"London Fish 'N Chips", @"Kenneth of London", @"Il Pastaio Fresh Pasta Company", @"Everett & Jones Barbeque", @"Duke of Edinburgh"];
NSArray *sorted = specialSort(arr, @"london");
NSLog(@"%@", sorted);
}
return 0;
}
» ./arraysort
2014-08-08 09:23:41.506 arraysort[81545:507] (
"Kenneth of London",
"London Fish 'N Chips",
"Antonik's BBQ",
"Jigsaw Salon",
"Il Pastaio Fresh Pasta Company",
"Everett & Jones Barbeque",
"Duke of Edinburgh"
)
»
答案 1 :(得分:0)
代码看起来不错。我通过以下示例检查了您的程序:
NSArray *arr = @[@"Antonik's BBQ", @"Jigsaw Salon", @"London Fish 'N Chips", @"Kenneth of London", @"Il Pastaio Fresh Pasta Company", @"Everett & Jones Barbeque", @"Duke of Edinburgh"];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"self CONTAINS[cd] %@", @"london"];
arr = [arr filteredArrayUsingPredicate:predicate];
我得到了:
(lldb) po arr
<__NSArrayI 0x10d599a50>(
London Fish 'N Chips,
Kenneth of London
)
我唯一的区别就是将title
更改为self
,并将字符串直接更改为数组。