如何将NSMutableDictionary setObject值分配为indexPath.section值?

时间:2018-07-26 07:33:19

标签: ios objective-c uicollectionview nsdictionary

我有NSMutableDictionary,返回结果如下:-

NSMutableDictionary *result = [NSMutableDictionary new];
        distinctNames = [_aryClippedCategoryList valueForKeyPath:@"@distinctUnionOfObjects.category_id"];
        for (NSString *category_id in distinctNames) {
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category_id = %@", category_id];
            NSArray *category_group = [_aryClippedCategoryList filteredArrayUsingPredicate:predicate];
            [result setObject:category_group forKey:category_id];

NSLog(@"123 - %@", result); 
NSLog(@"223 - %lu", (unsigned long)distinctNames.count); 

在NSLog 123中,结果将类似于:-

 17 =     (
                {
            "category_id" = 17;
            "category_name" = "Apparel & Accessories";
            "sub_category_id" = 17;
            "sub_category_name" = "Fashion jewelry";
        },
                {
            "category_id" = 17;
            "category_name" = "Apparel & Accessories";
            "sub_category_id" = 16;
            "sub_category_name" = Wholesale;
        }   
    );
    20 =     (
                {
            "category_id" = 20;
            "category_name" = "Beauty & Personal Care";
             "sub_category_id" = 288;
            "sub_category_name" = "Pedicure & medicure";
        },
                {
            "category_id" = 20;
            "category_name" = "Beauty & Personal Care";
            "sub_category_id" = 285;
            "sub_category_name" = "Fragrances and perfumes";
        }
);

在NSLog 223中,结果将类似于:-

223 - 2

在这种情况下,如何在CollectionView中选择category_group作为节值,并在CollectionView单元格中显示每组项目(category_id,category_name,sub_category_id,sub_category_name)?

2 个答案:

答案 0 :(得分:1)

  • 不推荐),应该使用NSMutableArray而不是NSMutableDictionary。

    结构是

    Array<Dictionary<Array *> *> *
    

    代码是这样的

    NSMutableArray *groups = [NSMutableArray new];
    <# your code #>
    [groups addObject:@{
        @"category_id": category_id,
        @"infos": category_group
    }];
    

    然后

    NSString *groupID = groups[indexPath.section][@"category_id"]
    

    这是您需要用于各个部分的组值。

    NSArray *infos = groups[indexPath.section][@"infos"];
    NSDictionary *info = infos[indexPath.item];
    

    这是项目的对象dict

  • 推荐)或将您的data转换为object。 (对象NSMutableArray<Object *> *

    然后使用groups.count来获取节。

    groups[indexPath.section].categoryID
    

    这是sections所需的组值。

    group = groups[indexPath.section]
    object = group.infos[indexPath.item]
    

    这是items

  • 的对象值

答案 1 :(得分:0)

如果您这样使用NSLog:

NSLog(@"123 - %@", result); 
NSLog(@"223 - %lu", (unsigned long)distinctNames.count); 

您明确要求它是一个字符串值,并且不会计算任何方程式。

如果要将结果打印为Integer,则必须这样做:

NSLog(@"%@", 123 - result); 
NSLog(@"%lu", 223 - (unsigned long)distinctNames.count); 

第一个参数是字符串格式,下一个参数将用于替换此字符串中的%。因此,您的计算必须在右侧完成。

要使其更加可见,最好是在NSLog之前创建结果为局部变量。