0

我有一个要在其中搜索的应用程序。我有一个数组 resultArray ,其中包含所有显示的内容

 Book*bookObj=[resultArray objectAtIndex.indexPath.row];
 NSString*test=bookObj.title;

如果在文本字段中输入的搜索文本与任何数组的标题匹配,我想对 resultArray 中的标题项执行搜索,然后将所有数组值复制到 testArray 中。

4

4 回答 4

0

- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate正是您想要的功能。它将返回一个新数组,其中仅包含NSPredicate对象中通过测试的元素。

例如:

NSArray *newArray = [oldArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Book *evaluatedObject, NSDictionary *bindings) {
    //Do whatever logic you want to in here
    return [evaluatedObject.title isEqualToString:theTitle];
}];
于 2013-08-19T08:05:44.850 回答
0

为此,您必须使用另一个数组。这将添加您的对象

for (Book * bookObj in resultArray) {
         NSString *strName=[[bookObj.title]lowercaseString];
         if ([strName rangeOfString:searchText].location !=NSNotFound) {
                [arrTemp addObject:bookObj];
            }
        }
于 2013-08-19T08:05:47.853 回答
0

将此用作:

   NSMutableArray *searchDataMA = [NSMutableArray new];

       for (int i = 0; i < resultArray.count; i++) {

         Book *bookObj=[resultArray objectAtIndex:i];
         NSString*test=bookObj.title;
        NSRange rangeValue1 = [test rangeOfString:searchText options:NSCaseInsensitiveSearch];

        if (rangeValue1.length != 0) {

            if (![resultArray containsObject:test]) {
                [searchDataMA addObject:test];
            }

        }
    }
于 2013-08-19T08:07:09.053 回答
0

它对我有用,试试这个:

NSArray *fruits = [NSArray arrayWithObjects:@"Apple", @"Crabapple", @"Watermelon", @"Lemon", @"Raspberry", @"Rockmelon", @"Orange", @"Lime", @"Grape", @"Kiwifruit", @"Bitter Orange", @"Manderin", nil];
NSPredicate *findMelons = [NSPredicate predicateWithFormat:@"SELF contains[cd] 'melon'"];
NSArray *melons = [fruits filteredArrayUsingPredicate:findMelons];
NSPredicate *findApple = [NSPredicate predicateWithFormat:@"SELF beginswith 'Apple'"];
NSArray *apples = [fruits filteredArrayUsingPredicate:findApple];
NSPredicate *findRNotMelons = [NSPredicate predicateWithFormat:@"SELF beginswith 'R' AND NOT SELF contains[cd] 'melon'"];
NSArray *rNotMelons = [fruits filteredArrayUsingPredicate:findRNotMelons];

NSLog(@"Fruits: %@", fruits);
NSLog(@"Melons: %@", melons);
NSLog(@"Apples: %@", apples);
NSLog(@"RNotMelons: %@", rNotMelons);

谓词还有更多的条件函数,其中一些我在这里只涉及到:

beginswith : matches anything that begins with the supplied condition
contains : matches anything that contains the supplied condition
endswith : the opposite of begins with
like : the wildcard condition, similar to its SQL counterpart. Matches anything that fits the wildcard condition
matches : a regular expression matching condition. Beware: quite intense to run

该语法还包含以下其他函数、谓词和操作:

AND (&&), OR (||), NOT (!)
ANY, ALL, NONE, IN
FALSE, TRUE, NULL, SELF

如果不明白,请查看此链接;

有用的链接

于 2013-08-19T08:20:40.267 回答