的UITableView - > numberOfRowsInSection不工作,因为我以为...
我目前有我的项目中以下问题:的UITableView - > numberOfRowsInSection不工作,因为我以为...
我使用的核心数据检索SQLite数据库的数据。我使用多个视图来显示数据库的不同部分。我还实现了一个searchBar来搜索整个数据库。由于我的数据可以划分为三个主要部分,通过布尔值,我告诉tableView如果状态是“搜索”有3个部分,否则整个取出的结果应该使用默认的核心数据功能分段分割。当我执行搜索时,检索到的数据按类型和标题排序,并复制到名为“searchResults”的NSMutableArray。我的数据模型有一个“类型”属性,我用它来知道给定元素属于哪个区域,我还想使用此属性来确定三个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];
}
}
BONUS:我注意到,对于部分标题头,而搜索(意思后,我得到了搜索结果),不要连同表与往常一样滚动,而是保持固定在他们的地方。相反,他们的副本似乎是做出来的,而且这些工作都是通常的方式。这怎么可能?
我发现问题:这是一个简单的错误!我在那里做的是一次又一次地过滤同一个数组,所以,当它第一次没有任何对象时被过滤为无效。所以我刚刚通过更改if-else语句解决了如下问题:
// if (searching)
NSPredicate *grammarType;
if (section == 1) {
NSMutableArray *intermediateResults = [NSMutableArray arrayWithArray:searchResults];
grammarType = [NSPredicate predicateWithFormat:@"type == %@", @"Intermediate"];
[intermediateResults filterUsingPredicate:grammarType];
return [intermediateResults count];
} else if (section == 2) {
NSMutableArray *advancedResults = [NSMutableArray arrayWithArray:searchResults];
grammarType = [NSPredicate predicateWithFormat:@"type == %@", @"Advanced"];
[advancedResults filterUsingPredicate:grammarType];
return [advancedResults count];
} else {
NSMutableArray *basicResults = [NSMutableArray arrayWithArray:searchResults];
grammarType = [NSPredicate predicateWithFormat:@"type == %@", @"Basic"];
[basicResults filterUsingPredicate:grammarType];
return [basicResults count];
}
很简单吧? ;) 无论如何,我仍然没有第二个问题的答案:
“我注意到,部分的标题标题,而搜索(意思是我得到搜索结果后),不照常和桌子一起滚动,但保持固定在他们的位置。相反,他们的副本似乎是做出来的,而且这些工作都是通常的方式。这怎么可能?“
不禁注意到你有两个分支:(section == 1)
。也许这是令人困惑的事情?
哦,这只是一个错字...在代码中它是两个。我会马上修改这个问题! – 2011-05-08 22:37:13