0

我想知道,保存和发送数据的“正确”方法是什么。假设我们收到 JSON。它的结构是这样的:

  {
    id = 1;
    country_id = 298;
    date = "2012-11-08 14:00:36";
    name = "Mr. Blank";
    profile = "http://somewhere.com/user1234/profile.png";
  }

现在,我们有了 tableView,在 CustomCell 中我们显示个人资料图片、姓名和国家/地区 ID。点击后,我们想要转换到详细视图,我们再次显示个人资料图片,以及基于他的 id 的一些其他信息(基本上是新的 api 调用)。

现在,当我们收到第一个 JSON 时,我们应该考虑如何保存和发送像 id 和 profile pic 这样的值。

我知道两种方法,但我不确定它们是否“正确”。第一个是,一旦您的 json 到达,就将所有内容保存到数组中。所以它看起来像这样

NSMutableArray *idArr = [[NSMutableArray alloc]init];
NSMutableArray *picArr = [[NSMutableArray alloc]init];

    for (NSDictionary *recDict in jsonResults)
        {
            NSString *personsID = [recDict objectForKey:@"id"];
            [idArr addObject:personsID];
            NSString *pic = [recDict objectForKey:@"profile"];
            [picArr addObject:pic];

        }

这种方法有效,但是,它总是将我们在 JSON 中获得的所有内容保存到数组中。所以当有很多行时,需要很长时间(特别是如果图片很大)。我知道,异步加载可能是解决方案,但我想在这里谈谈原理。

另一种方法是直接从选定的单元格传递值。这意味着,在方法 didSelectRowAtIndexPath

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        MyCustomCell *cell = (MyCustomCell *)[tableView cellForRowAtIndexPath:indexPath];
    imageToSend = cell.profilePic.image; //we have UIImage *imageToSend;
    idToSend = cell.idLabel.text; //we have NSString *idToSend;
    [self performSegueWithIdentifier:@"showDetail" sender:self];
}

这种方法的优点似乎是,tableView 默认使用“lazyload”(这意味着它会在用户向下滚动时加载单元格),所以在我看来,与第一种方法相比,它可以节省时间。

请你能给我一些关于你如何传递价值观的见解吗?我知道您应该使用 prepareForSegue 方法,但您无权访问 indexPath.row 那里。(因此您可以确定从何处调用该 segue)

4

1 回答 1

1

我更喜欢第二个。您不需要保存所有图像,只需保存 URL。应该异步加载图像(我使用EGOImageLoading),然后您可以将图像或 URL 发送到新视图。

您可以使用 tableView indexPathForSelectedRow 从该行传递数据:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSIndexPath *path = [self.tableView indexPathForSelectedRow];
    YourObject *yourObject = [objectsArray objectAtIndex:path.row];
    [segue.destinationViewController setObject:yourObject];
}
于 2012-12-12T17:56:32.707 回答