如何创建NSDictionary数组

时间:2012-09-27 22:58:05

标签: iphone ios core-data nsarray nsdictionary

我想将我存储的信息提取到我的一个核心数据对象中,并将这些数据存储到NSArrayNSDictionary个对象中,以便我可以将此数组发送到其中一个我的观点并在tableview中显示数据。

但是我不太确定如何将NSDictionary放入NSArray,这是我的抓取请求,希望有人可以帮我把NSDictionary放进去一个NSArray ..我不知道如何做到这一点,因为我通过核心数据对象循环。

// Test listing all FailedBankInfos from the store
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Manuf" inManagedObjectContext:context];
        [fetchRequest setEntity:entity];

        NSError *error; 

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

        NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
        for (Manuf *manuf in fetchedObjects) {
            [tempManufacturerDictionary setObject:manuf.hasMod forKey:@"HASMOD"];
            [tempManufacturerDictionary setObject:manuf.isLocked forKey:@"ISLOCKED"];
            [tempManufacturerDictionary setObject:manuf.isReg forKey:@"ISREG"];
            [tempManufacturerDictionary setObject:manuf.main forKey:@"MAIN"];

            // How do I put the Dictionary above into an array?
        }

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

您可以在进入循环之前实例化NSMutableArray,并在每次迭代期间声明一个新的NSMutableDictionary,如下所示:

    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    NSMutableArray *array = [NSMutableArray array];
    for (Manuf *manuf in fetchedObjects) {
        NSMutableDictionary *tempManufacturerDictionary = [NSMutableDictionary dictionary];
        [tempManufacturerDictionary setObject:manuf.hasMod forKey:@"HASMOD"];
        [tempManufacturerDictionary setObject:manuf.isLocked forKey:@"ISLOCKED"];
        [tempManufacturerDictionary setObject:manuf.isReg forKey:@"ISREG"];
        [tempManufacturerDictionary setObject:manuf.main forKey:@"MAIN"];

        [array addObject:tempManufacturerDictionary];
    }

您还可以将获取请求的resultType设置为NSDictionaryResultType,并首先从获取请求中获取字典数组。

答案 1 :(得分:2)

就像使用addObject时的任何其他对象一样。

您需要使用NSMutableArray,而不是普通NSArray才能添加元素。如果您严格需要不可变版本,可以稍后将可变数组转换为普通数组。