在一个简单的测试应用程序中,我试图将名为“thisArray”的数组对象从MasterViewController
传递到DetailViewController
中名为“passedData”的字符串。我正在使用Storyboard,UIViewController
嵌入在导航控制器中。使用prepareForSegue
方法,我成功地在UIViewController
:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"pushData"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
DetailViewController *destViewController = segue.destinationViewController;
destViewController.passedData = [thisArray objectAtIndex:indexPath.row];
}
}
现在出于某些原因,我想使用didSelectRowsAtIndexPath
代替prepareForSegue
。我用过这个:
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableString *object = thisArray[indexPath.row];
detailViewController.passedData = object;
}
但它没有用。我使用了以下内容:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
NSMutableString *object = thisArray[indexPath.row];
detailViewController.passedData = object;
[self.navigationController pushViewController:detailViewController animated:YES];
}
但它也没有用。
问题:
1)如何正确撰写didSelectRowsAtIndexPath
以替换prepareForSegue
?
2)如果我使用didSelectRowsAtIndexPath
,我是否需要删除故事板中UIViewController
之间的segue连接?
3)如果视图控制器之间确实没有segue连接,我怎样才能使用didSelectRowAtIndexPath
在它们之间传递数据?
谢谢!
更新:根据我收到的答案和评论,我写了以下内容:
首先我删除了控制器之间的segue连接,设置了StoryBoard标识DetailViewController
,类的名称也是DetailViewController
。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIStoryboard* sb = [UIStoryboard storyboardWithName:@"DetailViewController"
bundle:nil];
UIViewController* vc = [sb instantiateViewControllerWithIdentifier:@"DetailViewController"];
NSMutableString *object = thisArray[indexPath.row];
detailViewController.passedData = object;
[self.navigationController pushViewController:detailViewController animated:YES];
}
但它因以下错误而崩溃:
***因未捕获的异常
NSInvalidArgumentException
而终止应用,原因是:'无法找到故事板 在包中命名为DetailViewController
答案 0 :(得分:10)
你的第二次尝试几乎是正确的。唯一不太正确的是从故事板中实例化视图控制器的方式:使用initWithNibNamed:
,这是您使用NIB而不是故事板。对于故事板,您需要:
UIStoryboard* sb = [UIStoryboard storyboardWithName:@"theStoryboardId"
bundle:nil];
// If this code is inside a method called by a controller that is itself instantiated
// from a storyboard, you can replace the above line with this.storyboard
UIViewController* detailViewController = [sb instantiateViewControllerWithIdentifier:@"DetailViewController"];
有关详细信息,请参阅this question。
完成替换后,您的代码应按预期工作。
编辑::以下是您的方法的外观:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIViewController* detailViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
NSMutableString *object = thisArray[indexPath.row];
detailViewController.passedData = object;
[self.navigationController pushViewController:detailViewController animated:YES];
}