有很多很好的教程来学习如何正确解析 XML,这里有一个快速的:
在.h
@interface ObjectName : ObjectSuperclass <NSXMLParserDelegate> {
NSMutableString *currentElement;
NSMutableString *childElement;
NSMutableDictionary *dictionary;
}
@end
在 .m 中,插入这些 NSXMLParser 委托方法:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = nil;
currentElement = [elementName copy];
if ([elementName isEqualToString:@"xmlParentElement"]) {
//This means the parser has entered the XML parent element named: xmlParentElement
//All of the child elements that need to be stored in the dictionary should have their own IVARs and declarations.
childElement = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//For all child elements, run this if statement.
if (currentElement isEqualToString:@"childElement") {
[childElement appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:@"parentElement"]) {
[dictionary addObject:childElement forKey:@"childElement"];
//And devise a system for indexing (this could be converting the address string in to an array and taking objectAtIndex:0.. any way you choose, add that object below:
[dictionary addObject:@"A" forKey@"index"];
}
}
现在已经完成了,使用常规的 UITableViewController 委托方法来创建表,此外,使用这些委托方法来创建侧索引:
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [dictionary objectForKey:@"index"];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
return index;
}