如何将多个对象添加到数组 - Objective C / iOS

时间:2012-11-17 20:05:47

标签: objective-c ios json

我刚接触Objective C

编程

这是我的困境:我正在从网上提取一个JSON文件,我可以向我的tableView显示其中一个元素(currDate),但现在我想显示更多。从下面的代码我得到它来显示currDate和prevDate

逻辑需要在此更改:

for (NSDictionary *diction in arrayOfEntry) {
    NSString *currDate = [diction objectForKey:@"Current Date"];
    a = currDate;
    NSString *prevDate = [diction objectForKey:@"Previous Date"];
    b = prevDate;     

    [array addObject:a]; 

    }
    [[self myTableView]reloadData];

我不确定我是否需要在此更改任何内容,但我附上它以显示我如何将数组显示到我的viewTable:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if(!cell)
{
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault     reuseIdentifier:CellIdentifier];
}

cell.textLabel.text = [array objectAtIndex:indexPath.row];
//cell.textLabel.text = [array objectsAtIndexes:indexPath.row];
return cell;
}

3 个答案:

答案 0 :(得分:0)

使arrayOfEntry全球化。在.h文件中

NSArray *arrayOfEntry;

numberOfRowsInSection

[arrayOfEntry count]

tableView: cellForRowAtIndexPath

NSString *currDate = [[arrayOfEntry objectAtIndex:indexPath.row] objectForKey:@"Current Date"]
NSString *prevDate = [[arrayOfEntry objectAtIndex:indexPath.row] objectForKey:@"Previous Date"]
cell.textLabel.text = [NSString stringWithFormat:@"%@   %@", currDate, prevDate];

答案 1 :(得分:0)

只需添加另一行:

[array addObject:a];
[array addObject:b];

答案 2 :(得分:0)

要将多个元素添加到目标c中的数组中,您需要使用:

 NSMutableArray *newArr = [NSMutableArray new];

然后:

[newArr addObject:dict1];

如果需要,可以在添加完对象后将您使用的NSArray设置为NSMutuableArray