-5

我从本地数据库中提取字典。我的数据库数组名称为aryTitle_DB结构如下所述。在目标c中创建字典数组

({ “日期”:13/9/2014; “标题”= “ABC” },{ “日期”:13/9/2014; “标题”= “DEF”} ,{“date”:13/9/2014; “title”=“ghi”},{“date”:14/9/2014; “title”=“abc”},{“date”二千〇一十四分之九; “标题”= “ABC”},{ “日期”:15/9/2014; “标题”= “DEF”})

我需要以下从阵列结构的类型aryTitle_DB

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

我在堆栈溢出和其他教程中做了很多搜索,但无法找到它。 请帮忙创建这样的数组结构。 帮助将是可观的。

+0

你的目标结构有点傻。你应该有一个按日期键入的字典,条目是标题数组(如果你想要上述结构,你将不得不经过这个结构,作为一个中间步骤。) – 2014-09-13 12:25:14

回答

0
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字段的格式化字符串。

0

在Objective-C中,没有泛型,事实上这只是与Swing一起提供的。 所以你的数据结构只是一个经典的NSArrayNSDictionary

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

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:方法将它添加到字典中。

编辑:添加算法解析DB答案

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 
+0

感谢您的快速回复,但事情是我从DB获取字典对象,这给了我上面的数组。我需要创建数组,这是我在提到的db数组中提到的问题。 – 2014-09-13 12:16:16

+0

我添加了一些示例代码 – cdescours 2014-09-13 12:43:46