Cesar Tejada
Cesar Tejada

Reputation: 81

Can you make an array of dictionaries in Objective-C?

I have an array which contains a list of the countries in the world. Is there any way I can make an array of dictionaries, which each dictionary contain a list of the countries depending on the alphabet. For example:

  NSArray =>

NSDictionary
    headerTitle => ‘A’
    rowValues => {”A”, “Aa”, “Aaa”, “Aaaa”}
NSDictionary
    headerTitle => ‘B’
    rowValues => {”B”, “Bb”, “Bbb”, “Bbbb”}
etc.

Upvotes: 0

Views: 88

Answers (3)

AlKozin
AlKozin

Reputation: 916

I would use the object for this purpose:

   @interface CountriesByLetter : NSObject

      @property (nonatomic, copy) NSString *letter;
      @property (strong, nonatomic) NSArray *countries;

   @end

And store this objects in an array.

Upvotes: 0

i_am_jorf
i_am_jorf

Reputation: 54600

If you want to achieve exactly what you have listed, you can do this:

NSArray* array = @[ 
    @{ 
        @"A" : @[ @"Aa", @"Aaa", @"Aaaa" ] 
     }, 
    @{ 
        @"B" : @[ @"Bb", @"Bbb", @"Bbbb" ] 
     }
];

Upvotes: 1

davecom
davecom

Reputation: 1498

Sure you can, but why not do it the other way around - have a dictionary with keys which are the letters of the alphabet, and values which are an array of countries that start with that letter. Here is how you could do it with literals:

NSDictionary *countriesListedByLetter = @{@"A" : @[@"Albania",@"Argentina"], @"B" : @[@"Bolivia", @"Burma"]};

Upvotes: 3

Related Questions