Steven
Steven

Reputation: 781

Using a nested NSMutableDictionary

simple question, I need to structure data in the following format:

UserID:
    1 {
        Name = Bob
        Surname = Hope
    }
    2 {
        ...

I can used an NSMutableDictionary to add a single layer with keys, but I am unable to create a child associate with a certain key.

I have tried creating a mutable dictionary and assigning that to a key:

NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];

NSArray *keys = [[NSArray alloc] initWithObjects:@"Name", @"Surname", nil];

NSArray *details = [[NSArray alloc] initWithObjects:@"Bob",@"Hope", nil];

NSDictionary *person = [[NSMutableDictionary alloc] initWithObjects:details forKeys:keys];

[dic setValue:@"1" forKey:@"id"];

[[dic objectForKey:@"id"] setDictionary: person];

Upvotes: 2

Views: 4175

Answers (2)

Akshay
Akshay

Reputation: 5765

I think it is better to use an array of dictionaries, each dictionary representing a user.

NSMutableArray *users= [[NSMutableArray alloc] init];

NSArray *keys = [[NSArray alloc] initWithObjects:@"Name", @"Surname", nil];

NSArray *details = [[NSArray alloc] initWithObjects:@"Bob",@"Hope", nil];

NSDictionary *person = [[NSMutableDictionary alloc] initWithObjects:details forKeys:keys];

[users addObject:person];

Upvotes: 1

vishy
vishy

Reputation: 3231

u can also set the objects for dictionary in this way

    [dic setObject:person forKey:@"id"];

Upvotes: 0

Related Questions