信不信由你,在问这个问题之前,我已经搜索了互联网。令人难以置信的是,我还没有找到一个很好的清晰示例,说明如何创建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);
最佳答案
您没有初始化activeMissions
,这就是为什么NSLog
语句输出null的原因(将消息发送到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]];
(请记住,该文件是自动发布的,您必须保留某种方式)。
关于iphone - 创建NSDictionary的NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6737001/