1

我有一个NSMutableArray由文本字段组成的。我想在用户在UISearchBar. 最初我不想在用户开始输入之前加载所有文本字段。只有用户开始输入需要加载的第一个字母建议。有什么帮助吗?

4

2 回答 2

3

有很多逻辑,但我把我的逻辑放在这里:

取两个NSMutableArray并将一个数组添加到另一个数组ViewDidLoad,例如,

self.listOfTemArray = [[NSMutableArray alloc] init]; // array no - 1
self.ItemOfMainArray = [[NSMutableArray alloc] initWithObjects:@"YorArrayList", nil]; // array no - 2 

[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray]; // add 2array to 1 array

并编写以下 UISearchBar 的委托方法

- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText
{
        NSString *name = @"";
        NSString *firstLetter = @"";

    if (self.listOfTemArray.count > 0)
         [self.listOfTemArray removeAllObjects];

        if ([searchText length] > 0)
        {
                for (int i = 0; i < [self.ItemOfMainArray count] ; i = i+1)
                {
                        name = [self.ItemOfMainArray objectAtIndex:i];

                        if (name.length >= searchText.length)
                        {
                                firstLetter = [name substringWithRange:NSMakeRange(0, [searchText length])];
                                //NSLog(@"%@",firstLetter);

                                if( [firstLetter caseInsensitiveCompare:searchText] == NSOrderedSame )
                                {
                                    // strings are equal except for possibly case
                                    [self.listOfTemArray addObject: [self.ItemOfMainArray objectAtIndex:i]];
                                    NSLog(@"=========> %@",self.listOfTemArray);
                                }
                         }
                 }
         }
         else
         {
             [self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray ];
         }

        [self.tblView reloadData];
}
}

输出显示在您的Consol.

此代码可能对您有所帮助。

于 2013-08-21T05:51:08.483 回答
0

我认为最好的方法是构建自己的 NSCompoundPredicate:

  NSString *nameVar = ...; //ex: smith m
    NSArray *names = ...; //ex: John Smith, Mary Smith

    NSArray *terms = [nameVar componentsSeperatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSMutableArray *subpredicates = [NSMutableArray array];

    for(NSString *term in terms) {
      if([term length] == 0) { continue; }
      NSPredicate *p = [NSPredicate predicateWithFormat:@"name contains[cd] %@", term];
      [subpredicates addObject:p];
    }

    NSPredicate *filter = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
    [fetchController setPredicate:filter];

享受编码!

于 2013-08-21T05:59:36.080 回答