iOS - 如何在交换机

时间:2017-05-19 13:08:51

标签: ios objective-c nsdictionary

我在无法理解的情况下挣扎。

这是我的代码:

for (CDDetailDpt* detailDpt in [((CDGlobalInfo*)object).details allObjects]) {
    NSMutableArray *array = [NSMutableArray array];
    [array addObject:detailDpt.numDept];

    NSLog(@"Department Number = %@", detailDpt.numDept);
    NSLog(@"Color Number = %@", detailDpt.color);

    switch ([detailDpt.color intValue]) {
        case 2:
            [_deptDict setValue:array forKey:detailDpt.color];
            break;
        case 3:
             [_deptDict setValue:array forKey:detailDpt.color];
            break;
        case 4:
            [_deptDict setValue:array forKey:detailDpt.color];
            break;
        default:
             [_deptDict setValue:array forKey:detailDpt.color];
            break;
    }
}

for (id key in _deptDict)
    NSLog(@"dept Dict = %@", [_deptDict objectForKey:key]);

让我解释一下:

我正在循环抛出CoreData对象,更准确地说,我有一个国家/地区每个部门的信息列表。 在这个详细对象中,我有departmentNumber,departmentName和colorNumber(从1到4,以便在地图上显示)。

我想循环每个部门,并根据颜色值(从1到4)我想填写一个NSDictionary与关键部门,其中键是颜色编号。

例如:

我的词典将包含关键字@" 1" (颜色编号= 1)等...每个键。

我的日志只显示1个值。我填写说我没有填写字典。

我尝试使用setValue,setObject ..我不知道我做错了什么..

编辑:

我在for循环中添加了一个数组,以便临时存储该值而不覆盖它。

我觉得我的Switch无用,如何根据特定颜色部门将我的部门编号数组添加到我的词典中的右键?

此外,我还添加了一些日志,以便您可以看到我确实有一些值。

记录:

Department Number = 14
Color Number = 2
Department Number = 41
Color Number = 2
Department Number = 59
Color Number = 2
Department Number = 89
Color Number = 3
Department Number = 79
Color Number = 3
Department Number = 27
Color Number = 3
Department Number = 36
Color Number = 3

1 个答案:

答案 0 :(得分:0)

您当前的代码会为源中的每个元素初始化数组,以便每个元素中只有一个元素。

如果您对数组addObject:,如果数组中已存在数组,则它可以正常工作。

像:

NSMutableDictionary *deptDict = [[NSMutableDictionary alloc] init];

for (DetailDpt *detailDpt in self.detailDpts) {
    NSString *key = detailDpt.color.stringValue;
    if ([deptDict valueForKey:key]) {
        [(NSMutableArray *)[deptDict valueForKey:key] addObject:detailDpt.numDept];
    } else {
        [deptDict setValue:[NSMutableArray arrayWithObject:detailDpt.numDept] forKey:key];
    }
}

NSLog(@"deptDict = %@", deptDict);

...返回:

deptDict = {
   2 =     (
      14,
      41,
      89
   );
   3 =     (
       79,
       27,
       36
   );
}