如何在Xcode中创建检索到的JSON值数组

时间:2013-03-31 05:17:09

标签: objective-c xcode arrays json

我有多个JSON对象,我必须为其检索值“title”。我成功地检索了每个“标题”值,但是,我不确定如何将所有这些标题值放入NSMutableArray,以后我可以填充UITableView

目前,storyTitle(一个NSString)会返回几个不同的字符串,但它们都是分开的。例如,控制台返回

2013-03-30 21:39:30.416 Appv0.1[32742:11303] (
    "Boys\U2019 lacrosse display drive at Watsonville Jamboree"
)

2013-03-30 21:39:31.799 Appv0.1[32742:11303] (
    "Volleyball teams currently undefeated midway through season"
)

2013-03-30 21:39:32.093 Appv0.1[32742:11303] (
    "Wrestling season ends with a CCS victory and 2 state berths"
)

如何将这些字符串组合成一个数组?提前致谢!任何帮助将不胜感激。

NSDictionary *res = [NSJSONSerialization JSONObjectWithData: returnData options:NSJSONReadingMutableLeaves error:&myError];

storyList =  [NSMutableArray alloc];

storyTitle = [res objectForKey:@"title"];

//create array of storyTitles
NSString * story1 = [NSString stringWithFormat:@"%@", storyTitle];
//not sure how to do this array part 
storyList = [NSMutableArray arrayWithObjects:story1,nil];

编辑:如果我这样做:

     for(int i = 0; i < 5; i++){
            storyTitle = [res objectForKey:@"title"];
            NSString * story1 = [NSString stringWithFormat:@"%@", storyTitle];
            [self.storyList addObject:story1];
        }

控制台返回

array: (
"Boys\U2019 lacrosse display drive at Watsonville Jamboree",
"Boys\U2019 lacrosse display drive at Watsonville Jamboree",
"Boys\U2019 lacrosse display drive at Watsonville Jamboree",
"Boys\U2019 lacrosse display drive at Watsonville Jamboree",
"Boys\U2019 lacrosse display drive at Watsonville Jamboree",)

如何让阵列拥有所有3个独立的故事?

2 个答案:

答案 0 :(得分:0)

所以基本上你想将字符串添加到数组中?

正如sapi所指出的,storyList如果你想重用它,它应该是一个属性。

@property(nonatomic, strong)NSMutableArray *storyList;

然后在你的init方法

self.storyList = [[NSMutableArray alloc]init];

然后在你的代码中的某个地方

storyTitle = [res objectForKey:@"title"];
[self.storyList addObject:storyTitle];

答案 1 :(得分:0)

您还需要迭代res字典的元素(以获取每个元素):

    NSMutableArray * storyList =  [[NSMutableArray alloc] init];
    for (id item in res) {
        [storyList addObject:[item[@"title"]]];
    }

注意:'item [@“title”]'是'[item objectForKey:@“title”]'的新ObjC语法。