NSDictionary add NULL keyvalue

2019-07-11 04:29发布

问题:

So I am creating a NSDictionary that is feeding a method data to be used, but some of the key values in the keys array will not always be filled with values.. Say I have 18 keys (which I do).. I might only use 5 during one call but 6 in the other or even all 18 at some points in my code.

What I would like to know is how can I add NULL values into those keys so later on when i look through the keyvalue pairs I can see which keys i need to worry about and which I can forget? so the question is, if i want to add nothing/null to a key how do I do that without causing errors or thinking its the end of the array nil..

This is what I have currently but its giving me a bad exe error as soon as I try to read the NSDicionary

NSDictionary *sendSeriesDictionary = [[NSDictionary alloc] init];

NSArray *keys = [NSArray arrayWithObjects:@"Code", @"MaID", @"MoID", @"SuID",@"SMID",@"Ye",@"KID",@"KBlID",@"KBk",@"CaID",@"Caer",@"Loe",@"Kepe",@"KTGroup",@"Cesc",@"LID",@"IN",@"LaID", nil];


NSArray *objects = [NSArray arrayWithObjects: NULL, manufactureIdString, modelIdString, subModelIdString, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, nil];

sendSeriesDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

just to let you know the key names will be changed this is just for testing/example out how to do this.

any help would be greatly appreciated.

回答1:

The NSNull class is designed for this. You just have to make sure that whatever is going to be using the collection checks for NSNull values.

NSArray *objects = [NSArray arrayWithObjects: [NSNull null], manufactureIdString, modelIdString, subModelIdString, [NSNull null], ..., nil];


回答2:

NSNull is what you are looking for.