NSPredicate搜索对象

时间:2012-05-22 10:01:32

标签: objective-c nspredicate

我必须通过引入搜索关键字并在运行中过滤来过滤对象数组。我该怎么做?

//this is my Article class
@property  int intID;
@property (nonatomic, strong) NSString *strName;
@property (nonatomic, strong) NSString *strTitle;
@property (nonatomic, strong) NSString *strDescription;
@property (nonatomic, strong) NSString *lang;
@property (nonatomic, strong) NSString *dateDate;
@property (nonatomic, strong) NSData *dataPicture;
@property (nonatomic, strong) NSString *link;
@property (nonatomic, strong) NSString *gallery;
@property int flag;
@property int subcat;
@property int cat;
@property int idpic;

我必须选择包含带有引入字符串

的文本的文章
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{   
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"strName MATCHES '.*(%@).*'", searchText];
    
    NSLog(@"%@", [NSString stringWithFormat:@"strName MATCHES '.*%@.*' OR strTitle MATCHES '.*%@.*'", searchText, searchText]);
    
    articleSearchArray=[NSMutableArray array];
    articleSearchArray = [NSMutableArray arrayWithArray:[allArticleArr filteredArrayUsingPredicate:predicate]];

    for(Article *article in articleSearchArray)
    {
        
        NSLog(@"Article id is %i", article.intID);
    }
    [mytableView reloadData];
    
}

1 个答案:

答案 0 :(得分:3)

[NSPredicate predicateWithFormat:@"strName contains[c] '%@'", searchText];

这个将使用不区分大小写的比较(用strName表示)获取数组中searchText属性包含[c]字符串的所有对象,其中我认为是你正在寻找的。 之后,您只需将充当数据源的NSArray设置为已过滤的数据源,然后执行reloadData