【问题标题】:How to get responseObject into cells in UITableView如何将 responseObject 放入 UITableView 中的单元格
【发布时间】:2016-01-28 17:57:36
【问题描述】:

我正在制作一个“添加朋友”功能,可以在其中搜索用户名。我有一个包含用户数组的responeObject。我只想为所有用户获取@"name" 对象,然后在 TableView 中列出它们。如果我搜索“e”,我会得到 3 个结果:

responseObject: (
    {
    id = 1;
    isUsersAccount = 0;
    name = Eshixf;
},
    {
    id = 3;
    isUsersAccount = 0;
    name = Neigstal;
},
    {
    id = 4;
    isUsersAccount = 0;
    name = Howie;
})

如何在 3 个不同的单元格中取出所有 3 个名称? 为什么我在运行带有这一行的代码时会出错?:

NSDictionary *nameDict = [[friendRow objectAtIndex:0]objectForKey:@"name"];

它给了我这个错误:

-[__NSCFArray objectForKey:]:无法识别的选择器发送到实例 0x7faec35f4d40

谢谢!

【问题讨论】:

  • [friendRow objectAtIndex:0] 返回 NSArray 而不是 NSDictionary。即使它在您调用objectForKey: 时返回NSDictionary,它也会返回NSString。顺便问一下friendRow是什么?
  • @meth sry,它是:friendRow = [[NSArray alloc]initWithObjects:responseObject, nil];
  • 但是我可以得到第一个对象/项目的名称

标签: objective-c uitableview afnetworking


【解决方案1】:

您可以通过对响应的简单迭代获得所有名称。

NSArray *response = friendRow[0]; // this is result dictionaries in an array. actually it is your responseObject.

//NSMutableArray *names = [NSMutableArray new];
names = [NSMutableArray new];//if declared outside the method, use this array as a dataSource for tableView.
for(NSDictionary *dict in response)
{
     [names addObject:dict[@"name"]];
}
NSLog("names %@", names);

//refresh your tableview;
[yourTableView reloadData];

编辑表格视图:

在接口中创建名称

NSMutableArray *names;

在委托方法中:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier     forIndexPath:indexPath];
    [cell.textLabel setText:names[indexPath.row]];
    return cell;
}

使用这种方法,tableview 会知道它需要多少个单元格。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

// Return the number of rows in the section.
     return [names count];
}

【讨论】:

  • Nvm,我想应该是 in response 而不是 names ;)!
  • 是的,我在发布答案后立即更改了它:) 抱歉。
  • 不!和 ty 寻求帮助 :) 最后一件事 - 我如何将这些值放入 cell.textLabel?我认为这个 TableView 的东西有点令人困惑:/@meth
  • 您应该使用此名称对 tableview 的数据源进行更改。但是如果你没有足够的关于UITableView的信息,你可以在网上找到很多教程。
  • 是的,我知道,但我似乎找不到这么有帮助的人。但我确实知道一点,我现在在 textlabel 中的内容是:cell.textLabel.text = [NSString stringWithFormat:@"Username %@", indexPath.row];
猜你喜欢
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
  • 1970-01-01
  • 2011-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多