我有一个基本上读取xml文件并在UITableView中显示结果的应用程序。我试图按“country”(xml文件元素的属性)对列表项进行分组,并将它们显示在UITableView Sections中。
目前我读取了xml文件并将每个Element存储为NSMutableArray中的自定义对象。该数组具有以下结构:
阵列: 0 => (标题,描述,日期,国家) 1 => (标题,描述,日期,国家) 2 => (标题,描述,日期,国家) 3 => (标题,描述,日期,国家)
我尝试创建另一个独特国家/地区数组,这些数据允许我正确创建部分标题,但我正在努力找到在每个部分标题下方显示正确项目的方法。
if(![countryArray containsObject:itemCountry]) //if country not already in array
{
[countryArray addObject:itemCountry]; //Add NSString of country name to array
}
当item循环遍历xml文件时,itemCountry是每个元素的country属性。
[countryArray count]; //gives me the amount of sections needed
所以我想我的问题是我如何确定每个部分需要进行多少行? 如何为每个部分显示正确的数组项?
任何帮助或指示都会很棒
答案 0 :(得分:21)
您应该考虑创建字典,而不是创建包含数据的自定义对象数组。
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]
。
答案 1 :(得分:3)
对于使用Deepak答案的章节标题,请转到:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [self.sortedCountries objectAtIndex:section];
}
答案 2 :(得分:0)
您可能不应创建多个数组,而是创建一个字典数组。因此,创建一个名为counties或wtv的可变数组和包含标题,名称等的广告词典。要创建一个字典,只需创建一个NSMutableDictionary
对象然后使用setValue:forKey:
metod添加事情。对于国家/地区名称,值将是名称,密钥将按国家/地区。希望有所帮助。