【发布时间】:2011-05-08 14:06:13
【问题描述】:
我目前在我的项目中遇到以下问题:
我正在使用 Core Data 从 SQLite 数据库中检索数据。我使用多个视图来显示数据库的不同部分。我还实现了一个 searchBar 来搜索整个数据库。由于我的数据可以分为三个主要部分,因此我通过一个 BOOL 值告诉 tableView 如果状态为“正在搜索”则有 3 个部分,否则将使用默认的 Core Data 功能将整个获取的结果适当地划分为部分。当我执行搜索时,检索到的数据按类型和标题排序,然后复制到名为“searchResults”的 NSMutableArray。我的数据模型有一个 “type” 属性,我用它来知道给定元素属于哪个区域,我还想使用这个属性来确定三个 tableView 部分中的每个部分应该有多少行(如果一个部分的元素数量为 0,则该部分应显示为空,而其他部分则填充匹配的元素)。我正在使用以下代码来执行此操作,但它根本不起作用!如您所见,在我的 numberOfRowsInSection 方法中有一个 if-else if-else 控制结构,但我在每个条件中执行的操作的结果始终为“null”。 (对我来说)奇怪的是,如果我在控制结构之外执行任何这些操作,结果正是它应该是的!它给了我正确的行数(当然所有部分都是一样的)! 有什么问题?(在代码上方你会发现一个额外的问题:D)。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (searching) {
NSPredicate *grammarType;
if (section == 1) {
grammarType = [NSPredicate predicateWithFormat:@"type == %@", @"Intermediate"];
[searchResults filterUsingPredicate:grammarType];
return [searchResults count];
} else if (section == 2) {
grammarType = [NSPredicate predicateWithFormat:@"type == %@", @"Advanced"];
[searchResults filterUsingPredicate:grammarType];
return [searchResults count];
} else {
grammarType = [NSPredicate predicateWithFormat:@"type == %@", @"Basic"];
[searchResults filterUsingPredicate:grammarType];
return [searchResults count];
}
//If, instead, I use the following it works!
/*grammarType = [NSPredicate predicateWithFormat:@"type == %@", @"Basic"];
[searchResults filterUsingPredicate:grammarType];
return [searchResults count];*/
} else {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
}
奖励:我注意到部分的标题在搜索时(意思是在我得到搜索结果之后)不会像往常一样与表格一起滚动,而是保持不变在他们的地方。取而代之的是,它们的副本似乎已制作出来,并且以通常的方式工作。怎么可能?
【问题讨论】:
标签: uitableview core-data nspredicate