我有一个应用程序将数据保存到Core Data sql然后在表视图中查看它.
数据模型:
Entity: Fruits
Attributes: name, picture
Run Code Online (Sandbox Code Playgroud)
所以在表视图中,cell.textLabel.text = Fruits.name
每个单元格都有一个segue,其中的视图显示Fruits.picture.
我想添加一个搜索栏来搜索Fruits的名字.
我按照这个教程:http://www.appcoda.com/search-bar-tutorial-ios7/
但我遇到的问题是filterContentForSearchText
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
searchResults = [recipes filteredArrayUsingPredicate:resultPredicate];
}
Run Code Online (Sandbox Code Playgroud)
我使用的是核心数据,而不是用于存储数据的数组.我不知道如何过滤它,所以我可以在表格单元格中显示searchResults并在prepareForSegue中使用它.
由于您使用的是核心数据而不是Fruit数组,因此您应该以这种方式过滤数据:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Fruits" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray* searchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
}
Run Code Online (Sandbox Code Playgroud)
要在第二个viewController中显示图片,您应该在prepareForSegue方法中添加这样的内容:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
Fruit *selectedItem;
if (self.searchDisplayController.active) {
selectedItem = [searchResults objectAtIndex:indexPath.row];
} else {
selectedItem = [fruitsList objectAtIndex:indexPath.row];
}
DestinationViewController *destination = segue.destinationViewController;
destination.fruit = selectedItem;
}
Run Code Online (Sandbox Code Playgroud)
fruitsList是一个包含所有水果对象的数组(用于显示没有任何过滤器的水果的对象),并且DestinationViewController是显示图片的控制器.
| 归档时间: |
|
| 查看次数: |
4123 次 |
| 最近记录: |