Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store an NSArray in an NSDictionary?

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?

like image 743
john Avatar asked Jul 01 '10 05:07

john


People also ask

Does NSDictionary retain objects?

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 .

How do you set a value in NSDictionary?

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.

What is the difference between NSMapTable vs NSDictionary?

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.

Can NSArray contain nil?

arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.


1 Answers

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.

like image 88
Jason Coco Avatar answered Sep 20 '22 20:09

Jason Coco