如何在iphone中的数组中存储NSDictionary值

时间:2011-07-25 05:35:09

标签: iphone objective-c

    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder"]];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSDictionary *object = [parser objectWithString:json_string error:nil];
    NSArray *results = [parser objectWithString:json_string error:nil];

NSDictionary *dictOne = [results objectAtIndex:0];

appDelegate.books = [[NSMutableArray alloc] init];

NSArray *activitiesArray = [dictOne objectForKey:@"events"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:0];
NSLog(@"%@ - %@", [dictOne objectForKey:@"date"]);

NSLog(@"%@ - %@", [dictTwo objectForKey:@"affectedDate"]);

我想将这两个NSDictionary值存储在一个数组中

2 个答案:

答案 0 :(得分:5)

NSMutableArray *dictArray = [NSMutableArray alloc] init];

[dictArray addObject:dictOne];
[dictArray addObject:dictTwo];

如果您想将其插入特定索引..

[dictArray insertObject:dictOne atIndex:0];
[dictArray insertObject:dictTwo atIndex:1];

参考此链接.. NSMutableArray Class Reference

答案 1 :(得分:1)

较短但同样有效的选择是:

NSMutableArray *dictArray = [NSMutableArray alloc] initWithObjects: dictOne, dictTwo, nil];

此代码将使用位置0中的dictOne和位置1中的dictTwo初始化数组。最后的nil用于向objective-c编译器指示此参数列表已完成。如果您尝试在第2位申请该项目,则会收到错误。

PS:如果您不打算在数组中添加或删除项目,也可以使用NSArray。