Ответ 1
Вместо создания массива пользовательских объектов, содержащих ваши данные, вы должны посмотреть на создание словаря.
NSMutableDictionary * theDictionary = [NSMutableDictionary dictionary];
// Here `customObjects` is an `NSArray` of your custom objects from the XML
for ( CustomObject * object in customObjects ) {
NSMutableArray * theMutableArray = [theDictionary objectForKey:object.country];
if ( theMutableArray == nil ) {
theMutableArray = [NSMutableArray array];
[theDictionary setObject:theMutableArray forKey:object.country];
}
[theMutableArray addObject:object];
}
/* `sortedCountries` is an instance variable */
self.sortedCountries = [[theDictionary allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
/* Save `theDictionary` in an instance variable */
self.theSource = theDictionary;
Позже в numberOfSectionsInTableView
:
- (NSInteger)numberOfSectionsInTableView {
return [self.sortedCountries count];
}
В tableView:numberOfRowsInSection:
:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[self.theSource objectForKey:[self.sortedCountries objectAtIndex:section]] count];
}
В tableView:cellForRowAtIndexPath:
:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
[..]
/* Get the CustomObject for the row */
NSString * countryName = [self.sortedCountries objectAtIndex:indexPath.section];
NSArray * objectsForCountry = [self.theSource objectForKey:countryName];
CustomObject * object = [objectsForCountry objectAtIndex:indexPath.row];
/* Make use of the `object` */
[..]
}
Это должно пройти весь путь.
Боковое примечание
Если бы они не представляли данные и просто получали подсчет стран, то лучшей альтернативой подходу PengOne является использование NSCountedSet
.
NSCountedSet * countedSet = [NSCounted set];
for ( NSString * countryName in countryNames ) {
[countedSet addObject:countryName];
}
Теперь все уникальные страны доступны в [countedSet allObjects]
, и подсчет для каждой страны будет [countedSet countForObject:countryName]
.