2011-07-18 118 views
1

信不信由你,我在查詢這個問題之前已經在網上搜索過。令人難以置信的是,我還沒有找到一個很好的例子,說明如何創建一個NSDictionary的NSDictionaries的創建NSDictionary的NSDictionary

這是我的代碼到目前爲止,但它打印空。有任何想法嗎?

// Here I am creating the dictionaries in the code until I start getting them from the server ;) 
NSArray *keys = [NSArray arrayWithObjects:@"mission", @"target", @"distance",@"status", nil]; 


NSArray *objectsA = [NSArray arrayWithObjects:@"tiger", @"bill", @"5.4km", @"unknown", nil]; 
NSDictionary *tiger = [NSDictionary dictionaryWithObjects:objectsA 
                forKeys:keys]; 

NSArray *objectsB = [NSArray arrayWithObjects:@"bull", @"roger", @"10.1km", @"you are dead", nil]; 
NSDictionary *bull = [NSDictionary dictionaryWithObjects:objectsB 
               forKeys:keys]; 

NSArray *objectsC = [NSArray arrayWithObjects:@"peacock", @"geoff", @"1.4km", @"target liquidated", nil]; 
NSDictionary *peacock = [NSDictionary dictionaryWithObjects:objectsC 
                forKeys:keys]; 

// activeMissions = [NSArray arrayWithObjects:tiger, bull, peacock, nil]; 


[activeMissions setObject:tiger forKey:@"tiger"]; 
[activeMissions setObject:bull forKey:@"bull"]; 
[activeMissions setObject:peacock forKey:@"peacock"]; 

NSLog(@"active Missions %@", activeMissions); 

回答

8

你是不是intializing activeMissions,這就是爲什麼NSLog語句是印刷空(發送消息給ObjC返回nil nil對象)。

分配給activeMissions之前將這個:

NSMutableDictionary *activeMissions = [NSMutableDictionary dictionaryWithCapacity:3]; 

否則,如果你喜歡有一個非可變NSDictionary,你可以這樣做:

NSDictionary *activeMissions = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:tiger, bull, peacock, nil] 
                forKeys: [NSArray arrayWithObjects:@tiger, @"bull", @"peacock", nil]]; 

(請記住,這是自動釋放,你不得不保留)。