У меня проблемы с попыткой разобрать файл XML и отобразить результаты, сгруппированные по свойству объекта в UITableView.Это XML-файл, я могу изменить структуру, если это необходимо:
<Anuncios>
<Anuncio id="1">
<localeName>name1</localeName>
<address>address1</address>
<type>A</type>
</Anuncio>
<Anuncio id="2">
<localeName>name2</localeName>
<address>address2</address>
<type>B</type>
</Anuncio>
<Anuncio id="3">
<localeName>name3</localeName>
<address>address3</address>
<type>A</type>
</Anuncio>
</Anuncios>
На данный момент у меня есть NSMutableArray, называемый servs, содержащий объекты (Anuncio).
Это структура:
@interface Anuncio : NSObject
NSInteger iden;
NSString *localeName;
NSString *address;
NSString *type;
Итак, я хотел бы отсортировать UITableView по anuncio.type с правильным titleForHeaderInSection.
Я скачал TableViewSuite из документации Apple, и второй пример, SimpleSectionedTableView, кажется,делать то, что я хочу, но вместо того, чтобы получать данные из XML-файла, он получает данные, вызывая [NSTimeZone knownTimeZoneNames], поэтому структура совершенно иная, я попытался адаптировать пример кода для своего проекта, но я начинаюосознать, что это не самый лучший способ сделать это.Так что я немного застрял.
Я думал о том, чтобы внутри основного массива содержались массивы, содержащие объекты, редактирующие XML, например:
servs: {
arrayA : { anuncio1, anuncio3 }
arrayB : { anuncio2 }
}
, но тогда я не знаюкак завершить методы tableView.
Вот код XMLParse:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:@"Anuncios"]) {
//Initialize the array.
appDelegate.servs = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:@"Anuncio"]) {
//Initialize the anuncio.
serv = [[Anuncio alloc] init];
//Extract the attribute here.
serv.iden = [[attributeDict objectForKey:@"id"] integerValue];
NSLog(@"Reading id value: %i", serv.iden);
}
NSLog(@"Processing Element: %@", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];
NSLog(@"Processing Value: %@", currentElementValue);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:@"Anuncios"])
return;
if([elementName isEqualToString:@"Anuncio"]) {
[appDelegate.servs addObject:serv];
[serv release];
serv = nil;
}
else
[serv setValue:currentElementValue forKey:elementName];
[currentElementValue release];
currentElementValue = nil;
}
Часть моего текущего UITableViewController:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [appDelegate.servs count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
anuncios = (NSMutableArray *)[appDelegate.servs sortedArrayUsingSelector:@selector(compare:)];
Anuncio *anuncio = [anuncios objectAtIndex:section];
return [anuncio type];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
anuncios = (NSMutableArray *)[appDelegate.servs sortedArrayUsingSelector:@selector(compare:)];
Anuncio *anuncio = [anuncios objectAtIndex:indexPath.section];
cell.textLabel.text = anuncio.localeName;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
На данный момент я получаю:
A
--------
name1
--------
A
--------
name3
--------
B
--------
name2
и я хотел бы получить:
A
--------
name1
name3
--------
B
--------
name2
Я не знаю, правильная ли модель, которую я предлагаю, или я что-то упускаю.Я думал, что это было что-то очень распространенное, но я ничего не нашел по этому поводу.Спасибо за помощь