0

我正在尝试按顺序组织这个 json 数据......

{"message":["Untitled1b","Untitled2b","Untitled3b"],"name":["Untitled1a","Untitled2a","Untitled3a"]}

……这样红……

NSString *fileContent = [[NSString alloc] initWithContentsOfFile:getImagePath2];  

SBJsonParser *parser = [[SBJsonParser alloc] init];

NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];  

// getting the data from inside of "menu"  

//NSString *message = (NSString *) [data objectForKey:@"message"];
 //NSString *name = (NSString *) [data objectForKey:@"name"];

NSArray *messagearray = [data objectForKey:@"message"];
NSArray *namearray    = [data objectForKey:@"name"];


NSDictionary* Dictionary = [NSDictionary dictionaryWithObjects:messagearray forKeys:namearray];

f = namearray.count;
NSLog(@"happt = %i", f);

//namegroup.text = [NSString stringWithFormat:@"%@  %@",name, message];

g= 0;

do{

    NSArray *allKeys = [Dictionary allKeys];
    for (int i = 0; i < [allKeys count]; i++) {
        NSString *key = [allKeys objectAtIndex:i];
        NSObject *obj = [Dictionary objectForKey:key];
        // do something 

如您所见,在 json 文件中,消息和名称(数据对)的顺序正确(1a,1b ...)。对于每对数据,我创建 2 个文本视图并显示数据。对显示正确,但混淆了。我的意思是,我希望它们以 JSON 文件顺序显示(首先是 1a、1b,然后是 2a、2b,然后是 3a、3b...,而不是 2a、2b,然后是 1a、1b,然后是 3a、3b... )

我试着用这个:

NSSortDescriptor *dateSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"date"     ascending:NO selector:@selector(compare:)] autorelease];
[list sortUsingDescriptors:[NSArray arrayWithObjects:dateSortDescriptor, nil]];

......但它没有工作!请帮忙!!

4

1 回答 1

0

NSDictionary对象是无序的。键的顺序通常由搜索它们的最有效方式确定,这不太可能与它们添加到字典中的顺序相同。在任何情况下,an 中键的顺序NSDictionary通常不是您希望它们的顺序。如果要对键进行排序,可以使用:

NSDictionary *dict = /* fill your dictionary */;

NSArray *allKeys = [dict allKeys];

NSArray *sortedKeys = [allKeys sortedArrayUsingSelector:@selector(compare:)];

for (NSString *key in sortedKeys)
{
    id value = [dict objectForKey:key];

    // do something with "key" and "value" in sorted order of "key"
}
于 2012-05-13T21:02:44.977 回答