gpt4 book ai didi

iOS CoreData NSPredicate 一次查询多个属性

转载 作者:IT王子 更新时间:2023-10-29 08:04:14 27 4
gpt4 key购买 nike

我正在尝试使用 UISearchBar 查询 NSManagedObject 的多个属性我有一个名为 PersonNSManagedObject,每个人都有一个 namesocialSecurity 属性。现在,我的代码可以对这些属性之一或另一个执行搜索(获取),但不能同时执行这两个属性。

- (void) performFetch
{
[NSFetchedResultsController deleteCacheWithName:@"Master"];

// Init a fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MainObject" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

// Apply an ascending sort for the color items
//NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Term" ascending:YES selector:nil];
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES selector:@selector(caseInsensitiveCompare:)];

NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];
[fetchRequest setSortDescriptors:descriptors];

// Recover query
NSString *query = self.searchDisplayController.searchBar.text;
//if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"Term contains[cd] %@", query];
if(searchValue==1)
{
if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query];
}
else {
if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query];
}

// Init the fetched results controller
NSError *error;
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"pLLetter" cacheName:nil];

self.fetchedResultsController.delegate = self;

if (![[self fetchedResultsController] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]);

[self.tableView reloadData];
}

我不知道如何将这两个属性放入此语句中...

if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query];

如有任何帮助或想法,我们将不胜感激。

最佳答案

你可以使用 NSCompoundPredicate .

像这样:

NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query];
NSPredicate *predicateSSID = [NSPredicate predicateWithFormat:@"socialSecurity contains[cd] %@", query];
NSArray *subPredicates = [NSArray arrayWithObjects:predicateName, predicateSSID, nil];

NSPredicate *orPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];

request.predicate = orPredicate;

AND 也有一个NSCompoundPredicate:andPredicateWithSubpredicates:

关于iOS CoreData NSPredicate 一次查询多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10611362/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com