信不信由你,我在问这个问题之前已经在互联网上搜索过了。令人难以置信的是,我还没有找到一个很好的明确示例,说明如何创建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);
答案 0 :(得分:8)
你没有初始化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]];
(请记住,这是自动释放的,你必须以某种方式保留)。