如何使用iOS中的动态部分对tableview进行分组

时间:2012-11-22 17:23:24

标签: iphone ios xcode json

我调用web服务并获得一个不错的JSON作为回报。此JSON列出了几个带类别的报告。

最大的问题是我如何根据类别制作漂亮的桌面视图。我是iOS新手,我真的很痴心于此。

我将json保存在这样的数组中:

tableData = [NSJSONSerialization JSONObjectWithData:dataWebService options:kNilOptions error:&error];

然后我对列表进行排序:

NSArray *sortedArray;
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"Category"  ascending:YES];
sortedArray = [tableData sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];

我得到的json是这样的:

{
        Category = Faktura;
        about = "Fakturablankett med giro med utvalg p\U00e5 fra-til fakturanr";
        name = Faktura;
        reportendpoint = "https://unionline.unimicro.no/uni24Report/Report.aspx";
        reportid = 16;
    },
            {
        Category = Faktura;
        about = "Fakturablankett med giro med utvalg p\U00e5 fra-til fakturanr";
        name = "Faktura med sidenummer";
        reportendpoint = "https://unionline.unimicro.no/uni24Report/Report.aspx";
        reportid = 19;
    },
            {
        Category = Faktura;
        about = "Liste over fakturaer med status og mva-detaljer. Utvalg p\U00e5 fra-til fakturanr.";
        name = Fakturajournal;
        reportendpoint = "https://unionline.unimicro.no/uni24Report/Report.aspx";
        reportid = 15;
    },
            {
        Category = "Journaler og Kontoutskrifter";
        about = "";
        name = "Kontoutskrift hovedbok";
        reportendpoint = "https://unionline.unimicro.no/uni24Report/Report.aspx";
        reportid = 4;
    },
            {
        Category = "Journaler og Kontoutskrifter";
        about = "";
        name = "Kontoutskrift kunder";
        reportendpoint = "https://unionline.unimicro.no/uni24Report/Report.aspx";
        reportid = 5;
    }

我想在tableview中列出这些“名称”,按“类别”分组。我需要将类别排序为属于这些类别的报告的列表。

还有更多类别,但我没有将它们全部粘贴。

1 个答案:

答案 0 :(得分:4)

您必须创建一个具有类别数组列表的全局数组。

使用称为类别数组的元素创建全局数组,使用didReceiveResponseJson:nameDitionaryAllReadyExist:方法。

在UITableView中查看上面的json数据:

NSMutableArray* tableArray;//Declare this array globally and allocate memory in viewdidload

-(NSMutableArray *)nameDitionaryAllReadyExist:(NSString *)name {

    for(NSMutableArray *nameArray in tableArray){

        for(NSDictionary* nameDict in nameArray) {
            if([[nameDict objectForKey:@"Category"] isEqualToString:name])

                //return the existing array refrence to add
                return nameArray;
        }
    }

    // if we dont found then we will come here and return nil
    return nil;
}

-(void)didReceiveResponseJson:(NSArray *)jsonArray {

    for(NSDictionary* nameDict in jsonArray) {

        NSMutableArray* existingNameArray=[self nameDitionaryAllReadyExist:[nameDict objectForKey:@"Category"]];
        if(existingNameArray!=nil) {
            //if name exist add in existing array....
            [existingNameArray addObject:nameDict];
        }
        else {
            // create new name array
            NSMutableArray* newNameArray=[[[NSMutableArray alloc] init] autorelease];
            // Add name dictionary in it
            [newNameArray addObject:nameDict];

            // add this newly created nameArray in globalNameArray
            [tableArray addObject:newNameArray];
        }
    }

    //so at the end print global array you will get dynamic array with the there respetive dict.
    NSLog(@"Table array %@", tableArray);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    tableArray=[[NSMutableArray alloc] init];

    NSString* path=[[NSBundle mainBundle] pathForResource:@"JsonData" ofType:@"json"];

    NSDictionary* tableData=[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:kNilOptions error:nil];

    //NSLog(@"Table Array- %@",tableData);

    NSArray* dataArray = [tableData objectForKey:@"data"];

    [self didReceiveResponseJson:dataArray];
}

#pragma mark
#pragma mark UITableViewDataSource

//@required

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSArray* array=[tableArray objectAtIndex:section];
    return [array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        NSArray* array=[tableArray objectAtIndex:indexPath.section];

        NSDictionary* item=[array objectAtIndex:indexPath.row];
        NSString* name=[item valueForKey:@"name"];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    if (cell == nil) {
        // No cell to reuse => create a new one
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"] autorelease];        
        // Initialize cell
    }

    // Customize cell
    cell.textLabel.text = name;

    return cell;
}

//@optional

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return [tableArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

        NSArray* array=[tableArray objectAtIndex:section];
    if([array count]) {
        NSDictionary* item=[array objectAtIndex:0];
    return [item valueForKey:@"Category"];
    }
    else
        return nil;
}