Jon*_*Jon 6 iphone cocoa-touch core-data objective-c nsfetchedresultscontroller
我的应用程序中有一个UISearhBarController.它目前正在搜索在线数据库,但我正在将其更改为搜索核心数据数据库.它目前使用此代码:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if (self.billingSearchBar == searchBar) {
[self.billingSearchController filterResultsUsingString:searchText];
}
}
- (void)filterResultsUsingString:(NSString *)filterString
{
self.billingSearchText = filterString;
NSArray *billing_codes = [self billingSearch:self.billingSearchText searchType:self.billingSearchCategory];
self.displayedBillingSearch = billing_codes;
self.billingSearch = billing_codes;
[self.tableView reloadData];
}
-(NSMutableArray*)billingSearch:(NSString*)searchString searchType:(NSString*)searchType
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/server/20111115/60b88126/billing_search/", [self getHost]]];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:searchString forKey:@"query"];
[request setPostValue:searchType forKey:@"category"];
[request startSynchronous];
NSError *error = [request error];
NSString *responseString;
if (!error) {
responseString = [request responseString];
}
NSMutableArray *search_results = [[NSMutableArray alloc] init];
NSDictionary *responseDictionary = [responseString JSONValue];
for (id key in [responseDictionary valueForKey:@"search_results"]) {
[search_results addObject:key];
}
return search_results;
}
Run Code Online (Sandbox Code Playgroud)
所以我已经在核心数据中设置了数据库,我只需要将search/NSFetchedResults控制器连接到它.有什么简单的方法吗?
最简洁的方法是使用两个NSFetchedResultsControllers并将"搜索"NSFRC上的谓词设置为UISearchBar中的searchText.在确定要使用哪个NSFRC之后,只需设置self.fetchedResultsController ="搜索"NSFRC或"默认"NSFRC.
您也可以使用相同的NSFRC并更改谓词,但这不是推荐的方法.
见下面的评论.如果所有改变都是谓词,那么一个FRC就可以了.
以下是完成此操作的示例代码:
// First use the Searchbar delegate methods
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[self filterContentForSearchText:searchText];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[self filterContentForSearchText:searchBar.text];
[searchBar resignFirstResponder];
}
// The method to change the predicate of the FRC
- (void)filterContentForSearchText:(NSString*)searchText
{
NSString *query = searchText;
if (query && query.length) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@ or department contains[cd] %@", query, query];
[self.fetchedResultsController.fetchRequest setPredicate:predicate];
[self.fetchedResultsController.fetchRequest setFetchLimit:100]; // Optional, but with large datasets - this helps speed lots
}
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
// Handle error
exit(-1);
}
[self.myTableView reloadData];
}
Run Code Online (Sandbox Code Playgroud)
这应该开始了.
归档时间: |
|
查看次数: |
3056 次 |
最近记录: |