I'm trying to teach myself but am struggling with how to store something like an NSArray inside an NSDictionary.
Let's say hypothetically you had a NSDictionary for recipes:
Let's say the NSDictionary had keys like:
Spaghetti, Fettucine Alfredo, Grilled Chicken Salad
And the NSDictionary had an NSArray which was simply a list of ingredients.
I suppose the equivalent PHP code would be something like:
$['Spaghetti'] = array('Spaghetti Pasta', 'Spaghetti Sauce', 'Meatballs');
$['Fettucine Alfredo'] = array('Fettucine Pasta', 'Alfredo Sauce');
$['Grilled Chicken Salad'] = array('Lettuce', 'Grilled Chicken', 'Croutons');
I'm struggling with how I can add an NSArray to the NSDictionary. Then what if I wanted to remove an element or add an element to the array? How is it retrieved and deleted or added to?
An NSDictionary will retain it's objects, and copy it's keys. Here are some effects this has had on code I've worked on. Sometimes you get the same object you put in, sometimes not. Immutable objects are optimized to return themselves as a copy .
You have to convert NSDictionary to NSMutableDictionary . You have to user NSMutableDictionary in place of the NSDictionary . After that you can able to change value in NSMutableDictionary . Save this answer.
NSDictionary / NSMutableDictionary copies keys, and holds strong references to values. NSMapTable is mutable, without an immutable counterpart. NSMapTable can hold keys and values with weak references, in such a way that entries are removed when either the key or value is deallocated.
arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSArray arrayWithObjects:@"Spaghetti Pasta", @"Tomato Sauce", nil], @"Spaghetti",
[NSArray arrayWithObjects:@"Fettuccine Pasta", @"Alfredo Sauce", nil], @"Fettuccine Alfredo",
[NSArray arrayWithObjects:@"Lettuce", @"Grilled Chicken", @"Croutons", nil], @"Grilled Chicken Salad",
nil];
You can add any object type to a dictionary as a value. For more on dictionaries, see the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With