首页 文章

使用NSDictionaries的NSMutableArray创建一个Sectioned UITableView

提问于
浏览
0

我有一个 NSMutableArrayNSDictionaries ,我正在尝试格式化以使用 UITableView ,其中有一些基于 NSDictionary keys 之一的部分 .

我的 NSDicitonary 有两个值

Name
Key

键是数字1 - N的 NSString

我已经设法创建了一个 NSArray 的唯一值来填充每个部分的 Headers ,但是我不知道如何拆分这个NSDictionaries的NSArrays如果有意义的话 .

UPDATE: 为我的问题添加更多细节,我有一个NSDictionaries的NSMutableArray .

{
 Name: Jack
 Key: 1
}
{
 Name: John
 Key: 1
}
{
 Name: Jack
 Key: 1
}
{
 Name: Jack
 Key: 2
}
{
 Name: Jack
 Key: 3
}
{
 Name: Sean
 Key: 3
}
{
 Name: Sally
 Key: 3
}

我想在像这样的UITableView中显示它

Section 1
- Jack
- John
- Jack
Section 2
- Jack
Section 3
- Jack
- Sean
- Sally

我发现我需要做的事情是

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

我设法为部分创建了一个uniqueArray

uniqueKeys = [xmlMutableArray valueForKeyPath:@"@distinctUnionOfObjects.Key"];
    uniqueKeys = [uniqueKeys sortedArrayUsingComparator:^(id obj1, id obj2) {
        return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
    }];

现在我留下了如何在每个部分中找到行数然后将NSDictionary传递给cellforrow中的对象以向单元格显示正确值的情况?

任何帮助,将不胜感激 .

1 回答

  • 0

    希望对你有帮助:

    // testing
    NSMutableArray *test = [[NSMutableArray alloc]init];
    NSArray *testSample = @[@{@"1": @"hello1",@"2":@"world1",@"3":@"!1"},
                              @{@"1": @"hello2",@"2":@"world2",@"3":@"!2"},
                              @{@"1": @"hello3",@"2":@"world3",@"3":@"!3"}];
    [test addObjectsFromArray:testSample];
    NSMutableArray *sortedTestArray = [[NSMutableArray alloc] init];
    NSLog(@"%@",test);
    
    //get the max length of the nsdictionary
    NSDictionary *item0 = [test objectAtIndex:0];
    NSInteger maxLength = [[item0.allKeys lastObject] integerValue];
    //key start from @"1"
    for (int a = 1; a <= maxLength; a++) {
    NSString *keyNumber = [NSString stringWithFormat:@"%d", a];
    NSArray *sortedItem = [test valueForKey:keyNumber];
    //the index starts from 0
    [sortedTestArray insertObject:sortedItem atIndex:a-1];
    }
    //now the array will be like this,so the item in index 0 will be the key @"1"'s items. index 1 will be the key @"2"'s items...
    NSLog(@"%@",sortedTestArray);
    

    其原始数据:

    (
            {
            1 = hello1;
            2 = world1;
            3 = "!1";
        },
            {
            1 = hello2;
            2 = world2;
            3 = "!2";
        },
            {
            1 = hello3;
            2 = world3;
            3 = "!3";
        }
    )
    

    排序后的输出:

    (
            (
            hello1,
            hello2,
            hello3
        ),
            (
            world1,
            world2,
            world3
        ),
            (
            "!1",
            "!2",
            "!3"
        )
    )
    

相关问题