Create a dictionary property list programmatically

后端 未结 4 1891
清酒与你
清酒与你 2021-02-06 00:40

I want to programatically create a dictionary which feeds data to my UITableView but I\'m having a hard time with it. I want to create a dictionary that resembles this property

4条回答
  •  旧巷少年郎
    2021-02-06 00:54

    NSMutableDictionary *topLevel = [NSMutableDictionary dictionary];
    
    NSMutableDictionary *item1 = [NSMutableDictionary dictionary];
    NSString *item1title = [NSString stringWithString:@"Title 1"];
    NSMutableDictionary *item1children = [NSMutableDictionary dictionary];
    
    //  create children
    NSString *item1child1 = [NSString stringWithString:@"item 1, child 1"];
    
    NSMutableDictionary *item1child2 = [NSMutableDictionary dictionary];
    NSString *item1child2title = [NSString stringWithString:@"Title 1-2"];
    NSMutableDictionary *item1child2children = [NSMutableDictionary dictionary];
    
    NSString *item1child2child1 = [NSString stringWithString:@"item 1, child 2, child 1"];
    NSString *item1child2child2 = [NSString stringWithString:@"item 1, child 2, child 2"];
    
    [item1child2 setObject:item1child2title forKey:@"Title"];
    [item1child2children setObject:item1child2child1 forKey:@"item 1 child2 child 1"];
    [item1child2children setObject:item1child2child2 forKey:@"item 1 child2 child 2"];
    
    [item1child2 setObject:item1child2children forKey:@"children"];
    
    //  add children to dictionary
    [item1children setObject:item1child1 forKey:@"item1 child1"];
    [item1children setObject:item1child2 forKey:@"item1 child2"];
    
    //  add to item 1 dict
    [item1 setObject:item1title forKey:@"Title"];
    [item1 setObject:item1children forKey:@"children"];
    
    NSMutableDictionary *item2 = [NSMutableDictionary dictionary];
    NSString *item2title        = [NSString stringWithString:@"Title"];
    NSMutableDictionary *item2children  = [NSMutableDictionary dictionary]; 
    
    NSString *item2child1 = [NSString stringWithString:@"item 2, child 1"];
    NSString *item2child2 = [NSString stringWithString:@"item 2, child 2"];
    NSString *item2child3 = [NSString stringWithString:@"item 2, child 3"];
    
    //  add children to dictionary
    [item2children setObject:item2child1 forKey:@"item2 child1"];
    [item2children setObject:item2child2 forKey:@"item2 child2"];
    [item2children setObject:item2child3 forKey:@"item2 child3"];
    
    //  add to item 2 dict
    [item2 setObject:item2title forKey:@"Title"];
    [item2 setObject:item2children forKey:@"children"];
    
    [topLevel setObject:item1 forKey:@"Item 1"];
    [topLevel setObject:item2 forKey:@"Item 2"];
    

提交回复
热议问题