【问题标题】:Create array of dictionaries in objective c在目标 c 中创建字典数组
【发布时间】:2014-09-13 11:54:24
【问题描述】:

我正在从本地数据库中获取字典。 我的名为 aryTitle_DB 结构的数据库数组如下所述。

({ “日期”:2014 年 13 月 9 日; “标题”=“abc” }, { "日期":13/9/2014; "title"="def" }, { "date":13/9/2014; "title"="ghi" }, {"日期":14/9/2014; "title"="abc" }, { "date":15/9/2014; "title"="abc" }, { "date":15/9/2014; "title"="def" })

我需要来自 aryTitle_DB

的以下类型的数组结构

( { "13/9/2014":("abc","def","ghi") }, { "14/9/2014":("abc") }, { "15/9/ 2014":("abc","def") })

我在堆栈溢出和其他教程中进行了大量搜索,但找不到。 请帮助创建这种数组结构。 帮助将是可观的。

【问题讨论】:

  • 你的目标结构有点傻。您应该有一个按日期键入的字典,条目是标题数组(如果您想要上述结构,则无论如何都必须通过此结构,作为中间步骤。)

标签: objective-c nsmutablearray nsarray nsdictionary nsmutabledictionary


【解决方案1】:
NSMutableArray *fromDB;
NSMutableArray *filtered;
filtered = [NSMutableArray new];
while (fromDB.count > 0){
    NSDictionary *uniqueDate;
    NSArray *filteredDate;
    NSMutableArray *newDate;
    uniqueDate = fromDB[0];
    filteredDate = [fromDB filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.date=%K",uniqueDate[@"date"]]];
    [fromDB removeObjectsInArray:filteredDate];
    newDate = [NSMutableArray new];
    for (NSDictionary *oneDate in filteredDate) {
        [newDate addObject:oneDate[@"title"]];
    }
    uniqueDate = @{uniqueDate[@"date"]:newDate};
    [filtered addObject:uniqueDate];
};

这段代码应该可以工作。可能应该更改谓词的格式,因为我没有测试它。代替格式,您可以使用带有填充 var 字段的格式化字符串。

【讨论】:

    【解决方案2】:

    在 Objective-C 中,没有泛型,这实际上只是在 Swing 中出现的。 所以你的数据结构只是一个经典的NSArrayNSDictionary

    如果你想在 objC 中声明这个 ( { "13/9/2014":("abc","def","ghi") }, { "14/9/2014":("abc") }, { "15/9/2014":("abc","def") } ),你可以这样做

    NSMutableArray* result = [NSMutableArray new];
    NSDictionary * dict = [NSDictionary new];
    // With Modern objective C syntax, it would be like that :
    dict["13/9/2014"] = @{"abc","def","ghi"};
    dict["14/9/2014"] = @{"abc"};
    dict["15/9/2014"] = @{"abc","def"};
    
    [result addObject:dict];
    

    当然,您可以为每个值创建中间的NSMutableArray,并使用NSDictionarysetValue:ForKey: 方法将其添加到字典中。

    编辑:添加算法来解析数据库答案

    NSArray*DBAnswer; // this is your array containing the answer from the DB
    NSDictionary*result=[NSDictionary new];
    for(NSDictionary*d in DBAnswer)
    {
        NSMutableArray*list;
        if(![result containsKey:d["date"]])
        {
           list = [NSMutableArray new];
           result[d["date"]] = list;
        } 
        else 
        { 
           list = result[d["date"]];
        }
        [list addObject:d["title"]];
    }
    
    // After that you have the structure in the result NSDictionary
    

    【讨论】:

    • 感谢您的快速回复,但问题是我正在从数据库中获取字典对象,这给了我上面的数组。我需要创建我在问题中提到的从获取数据库数组中提到的数组。
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    相关资源
    最近更新 更多