2012-05-13 154 views
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]]; 

...但它沒有工作!請幫忙!!

+1

當然您的排序描述符不工作,因爲你已經要求它根據'date'這個關鍵字對'list'(它沒有在你提供的代碼中的任何地方聲明)進行排序(在代碼中的任何地方提供*)。 – dreamlax

回答

0

NSDictionary對象無序。密鑰的順序通常由搜索它們的最有效的方式決定,這不可能與它們添加到字典中的順序相同。在任何情況下,密鑰在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" 
} 
+0

我不明白。你如何訂購Key sortedinKeys?我能不能按照json文件中顯示的順序對數據進行排序? – Alessandro

+0

和選擇器比較? – Alessandro

+0

我試過了上面的代碼,但它對訂單沒有任何影響 – Alessandro