我正在使用XML Parser来解析xml文件并将其存储为全局数据。我正在获取该数据并将其显示为表格。我正在使用此示例来包含搜索功能。
我想将数据显示为带有字母和标题的分组表视图...
喜欢--->> | A |
Adam
Apple...
以下是我在没有小组的情况下显示表格的方式:
-(UITableViewCell *) tableView : (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"acell"];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"acell"] autorelease];
}
if(searching)
{
Boat *copyboat = [copyListOfItems objectAtIndex:[indexPath row]];
cell.textLabel.text = [copyboat boatName];
NSLog(@"%@", [copyboat boatName]);
}
else {
NSSortDescriptor *alphaDesc = [[NSSortDescriptor alloc] initWithKey:@"boatName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
[[data boats] sortUsingDescriptors:[NSMutableArray arrayWithObjects:alphaDesc, nil]];
Boat *fullboat =[data.boats objectAtIndex:[indexPath row]];
cell.textLabel.text =[fullboat boatName];
[alphaDesc release];
}
return cell;
}
如何在表格视图中显示数据?
答案 0 :(得分:0)
您没有提及您的数据如何,您解析它的数据类型。我假设“全局数据”意味着可以在应用程序范围内访问的一些NSArray 如果你不这样做,你应该考虑使用CoreData。
我修改了Apples示例代码CoreDataBooks,以便它不使用作者名称来生成部分,而是使用它的第一个字母。
在实施RootViewController之前在Book上添加此类别:
@interface Book (FirstLetter)
- (NSString *)uppercaseFirstLetterOfName;
@end
@implementation Book (FirstLetter)
- (NSString *)uppercaseFirstLetterOfName {
[self willAccessValueForKey:@"uppercaseFirstLetterOfName"];
NSString *aString = [[self valueForKey:@"author"] uppercaseString];
NSString *stringToReturn = [aString substringToIndex:1];
[self didAccessValueForKey:@"uppercaseFirstLetterOfName"];
if ([stringToReturn integerValue] || [stringToReturn isEqualToString:@"0"] ) {
return @"#";
}
return stringToReturn ;
}
@end
在RootViewController的- (NSFetchedResultsController *)fetchedResultsController
getter
更改
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"author" cacheName:@"Root"];
到
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"uppercaseFirstLetterOfName" cacheName:@"Root"];
编辑回复评论
你可以使用NSDirectory,它将第一个字母保存为键,将NSArray保存为所有相关数据对象作为对象。
numberOfSectionsInTableView:
会返回[[theDirectory allKeys] count]
tableView:titleForHeaderInSection:
返回[[theDirectory allKeys] objectAtIndex:section]
。排序未在此处显示。tableView:numberOfRowsInSection:
返回[theDirectory objectForKey:[[theDirectory allKeys] objectAtIndex:section]]
tableView:cellForRowAtIndexPath:
中使用indexPath.section
和indexPath.row
来解析正确的数据。我没有测试过这个。