【问题标题】:How to add multiple Objects to Array - Objective C / iOS如何将多个对象添加到数组 - Objective C / iOS
【发布时间】:2012-11-17 20:05:47
【问题描述】:

我是 Objective C 编程新手

这是我的两难境地:我正在从网络中提取一个 JSON 文件,并且能够将其中一个元素 (currDate) 显示到我的 tableView 中,但现在我想显示更多。从下面的代码中,我可以让它同时显示 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;
}

【问题讨论】:

  • 那个for循环sn-p实际上是在这个里面:-(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil]; NSDictionary *feed= [allDataDictionary objectForKey:@"feed"]; NSArray *arrayOfEntry = [feed objectForKey:@"entry"]; ....for...blah blah blah

标签: objective-c ios json


【解决方案1】:

只需添加另一行:

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

【讨论】:

  • 是的,这就是我所做的,但是当我这样做时程序会崩溃,并且在这行代码上出现 SIGABRT 错误:cell.textLabel.text = [array objectAtIndex:indexPath.row];跨度>
  • 如何在 .h 文件中声明数组?您是否将其声明为强属性?
  • 实际上,我在评论中写的可能是错误的——你想如何呈现你的数据?你想 currDate 和 prevDate 在同一个单元格中吗?您必须为此使用不同的单元格类型。否则,您只会使用 currDate 和 prevDate、curate、prevDate 等交替行,这样就不好了。
  • 那么它在哪里以及如何定义?
  • 后者(交替行)
【解决方案2】:

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];

【讨论】:

  • 我应该如何处理我的 -(void)connectionDidFinishLoading:(NSURLConnection *)connection 我上面粘贴的 for 循环?
【解决方案3】:

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

 NSMutableArray *newArr = [NSMutableArray new];

然后:

[newArr addObject:dict1];

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    相关资源
    最近更新 更多