1

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

目前,storyTitle (a 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 个单独的故事?

4

2 回答 2

0

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

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

@property(nonatomic, strong)NSMutableArray *storyList;

然后在你的 init 方法中

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

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

storyTitle = [res objectForKey:@"title"];
[self.storyList addObject:storyTitle];
于 2013-03-31T05:28:43.410 回答
0

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

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

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

于 2013-04-01T17:41:18.463 回答