Believe it or not, I have searched the internet before asking this question. Unbelievably, I have yet to find a nice clear example of how to create an NSDictionary 开发者_运维问答of NSDictionaries.
Here is my code so far, but it prints null. Any ideas?
// 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);
You are not intializing activeMissions
, that is why the NSLog
statement is printing null (sending a message to a nil object in ObjC return nil).
Put this before assigning to activeMissions
:
NSMutableDictionary *activeMissions = [NSMutableDictionary dictionaryWithCapacity:3];
Otherwise, if you prefer having a non mutable NSDictionary
, you could do:
NSDictionary *activeMissions = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:tiger, bull, peacock, nil]
forKeys: [NSArray arrayWithObjects:@tiger, @"bull", @"peacock", nil]];
(Keep in mind that this is autoreleased, you'll have to retain somehow).
精彩评论