您应该考虑创建字典,而不是创建包含数据的自定义对象数组。
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]。