创建NSDictionaries的NSDictionary

Eri*_*tto 1 iphone cocoa-touch objective-c nsdictionary ios

信不信由你,我在问这个问题之前已经在互联网上搜索过了.令人难以置信的是,我还没有找到一个很好的明确示例,说明如何创建NSDictionaries的NSDictionary.

这是我到目前为止的代码,但它打印为null.有任何想法吗?

// 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);
Run Code Online (Sandbox Code Playgroud)

ser*_*gio 8

你没有初始化activeMissions,这就是NSLog语句打印为空的原因(向ObjC中的nil对象发送消息返回nil).

在分配给之前放这个activeMissions:

NSMutableDictionary *activeMissions = [NSMutableDictionary dictionaryWithCapacity:3];
Run Code Online (Sandbox Code Playgroud)

否则,如果你喜欢不可变NSDictionary,你可以这样做:

NSDictionary *activeMissions = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:tiger, bull, peacock, nil]
                                                  forKeys: [NSArray arrayWithObjects:@tiger, @"bull", @"peacock", nil]];
Run Code Online (Sandbox Code Playgroud)

(请记住,这是自动释放的,你必须以某种方式保留).