如果有匹配的项目,如何在数组上执行搜索,然后在ipad应用程序中将这些项目复制到另一个数组中

时间:2013-08-19 07:57:56

标签: ios arrays search copy

我有一个应用程序,我想要搜索。我有一个数组resultArray,其中包含所有显示为

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

我想在resultArray中对标题项执行搜索,如果在textfield中输入的搜索文本与任何数组的title匹配,则在testArray中复制所有数组值。

4 个答案:

答案 0 :(得分: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];
}];

答案 1 :(得分:0)

你必须为此采取另一个数组。这将添加您的对象

for (Book * bookObj in resultArray) {
         NSString *strName=[[bookObj.title]lowercaseString];
         if ([strName rangeOfString:searchText].location !=NSNotFound) {
                [arrTemp addObject:bookObj];
            }
        }

答案 2 :(得分: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];
            }

        }
    }

答案 3 :(得分: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

如果不明白,请看看这个链接;

Useful link