我想知道保存和发送数据的“正确”方法是什么。假设我们收到 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。单击后,我们希望转换到详细信息 View ,在其中再次显示个人资料图片,以及基于他的 ID 的其他一些信息(基本上是新的 api 调用)。
现在,当我们收到第一个 JSON 时,我们应该考虑如何保存和发送 id 和个人资料图片等值。
我知道两种方法,但我不确定它们是否“正确”。 第一个是,一旦 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)
最佳答案
我更喜欢第二个。您不需要保存所有图像,只需保存 URL 即可。图像应该异步加载(我使用 EGOImageLoading ),然后您可以将图像或 URL 发送到新 View 。
您可以使用 tableView indexPathForSelectedRow 传递该行的数据:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
YourObject *yourObject = [objectsArray objectAtIndex:path.row];
[segue.destinationViewController setObject:yourObject];
}
关于ios - 当数据以 JSON 形式出现时,保存数据并将其从 TableView Controller 发送到详细 View Controller 的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13845584/