I am trying to insert an object to an array of NSDictionary b开发者_Python百科ut cant find out how. all the examples show how to insert to an array with NSDictionary with insertObject:atIndex, but this one doesnt insert the object under a dictionary key.
My array right now is the following:
NSArray *aaa = [NSArray arrayWithObjects:@"Disable" ,nil];
NSDictionary *aaaDict = [NSDictionary dictionaryWithObject:aaa forKey:@"Computers"];
NSArray *bbb = [NSArray arrayWithObjects:@"Enable", nil];
NSDictionary *bbbDict = [NSDictionary dictionaryWithObject:bbb forKey:@"Computers"];
NSArray *ccc = [NSArray arrayWithObjects:@"Enable", nil];
NSDictionary *cccDict = [NSDictionary dictionaryWithObject:ccc forKey:@"Computers"];
[listOfItems addObject:aaaDict];
[listOfItems addObject:bbbDict];
[listOfItems addObject:cccDict];
I would like to do this, but with a key "Computers":
NSArray *ar = [NSArray arrayWithObjects:@"xxxx", @"yyyy", @"zzzz", nil];
NSDictionary *arDict = [NSDictionary dictionaryWithObject:ar forKey:@"Computers"];
[listOfItems insertObject:ar atIndex:1];
Again - it does add the new array but not under the key "Computers". What am I missing here?
Thanks!
You probably wanted to write
[listOfItems insertObject:arDict atIndex:1];
instead of
[listOfItems insertObject:ar atIndex:1];
You're adding the array and not the dictionary like in the first part of your question.
I'm not sure I understand exactly what you're trying to do, but did you mean to insert the ar object or the arDict object? I think your code should look like
NSArray *ar = [NSArray arrayWithObjects:@"xxxx", @"yyyy", @"zzzz", nil];
NSDictionary *arDict = [NSDictionary dictionaryWithObject:ar forKey:@"Computers"];
[listOfItems insertObject:arDict atIndex:1];
Do you mean you want to add another array to a dictionary inside your listOfItems array? If that is the case it requires a nested method call as such:
[[listOfItems objectAtIndex:0] setObject:ar forKey:@"Computers"];
When it adds the new object you have to get the NSDictionary first. So basically you are using the dictionary wrong. What you have done is equivalent to
[listOfItems addObject:aaa];
and similarly bbb and ccc and ar
What you actually want to do is add the objects to a Dictionary and not a array.
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary addObject:[NSArray arrayWithObjects:@"Disable" ,nil] forKey:@"Key1"]; // your keys need to be unique
[dictionary addObject:[NSArray arrayWithObjects:@"Enable", nil] forKey:@"Key2"];
[dictionary addObject:[NSArray arrayWithObjects:@"Enable", nil] forKey:@"Key3"];
[dictionary addObject:[NSArray arrayWithObjects:@"xxxx", @"yyyy", @"zzzz", nil] forKey:@"Key4"];
With leak fixed issue
NSArray *ar = [NSArray arrayWithObjects:@"xxxx", @"yyyy", @"zzzz", nil];
NSDictionary *arDict = [NSDictionary dictionaryWithObject:ar forKey:@"Computers"];
[listOfItems insertObject:arDict atIndex:1];
[ar release]; // fixed the leak
[arDict release]; // fixed the leak
精彩评论