UITableView分组来自NSMutableArray的部分

Leo*_*Leo 12 iphone uitableview nsmutablearray ios

我有一个基本上读取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
}
Run Code Online (Sandbox Code Playgroud)

其中itemCountry是每个元素的country属性,因为我循环遍历xml文件.

[countryArray count]; //gives me the amount of sections needed
Run Code Online (Sandbox Code Playgroud)

所以我想我的问题是我如何确定每个部分需要进行多少行?如何为每个部分显示正确的数组项?

任何帮助或指针都会很棒

Dee*_*olu 22

您应该考虑创建字典,而不是创建包含数据的自定义对象数组.

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;
Run Code Online (Sandbox Code Playgroud)

后来numberOfSectionsInTableView:

- (NSInteger)numberOfSectionsInTableView {
    return [self.sortedCountries count];
}
Run Code Online (Sandbox Code Playgroud)

tableView:numberOfRowsInSection::

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.theSource objectForKey:[self.sortedCountries objectAtIndex:section]] count];
}
Run Code Online (Sandbox Code Playgroud)

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` */

    [..]
}
Run Code Online (Sandbox Code Playgroud)

这应该带你一路走来.

附注
如果不是要提供数据并且只是获得国家的统计数据,那么替代PengOne的方法就是使用NSCountedSet.

NSCountedSet * countedSet = [NSCounted set];
for ( NSString * countryName in countryNames ) {
    [countedSet addObject:countryName];
}
Run Code Online (Sandbox Code Playgroud)

现在,每个国家都有可用的所有独特国家/ [countedSet allObjects]地区[countedSet countForObject:countryName].