假设我有 2 个 Controller ,BarViewController 和 FooViewController。

FooViewController 有一个名为 imageView 的 UIImageView 的导出:

@property (nonatomic, weak) UIImageView *imageView;

BarViewController 有一个 UIButton 按钮的导出。
BarViewController 有一个从此按钮到 FooViewController 的转接,称为 BarToFooSegue(在 Storyboard中完成)。

当我运行以下代码,并在 FooViewController.imageView.image 上调用 NSLog 时,结果为零,并且我的图像不会显示。为什么会这样?
// code in BarViewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    if([segue.identifier isEqualToString:@"BarToFooSegue"]){
        NSURL *photoUrl = @"http://www.randurl.com/someImage"; // assume valid url
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:photoUrl]];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

        [segue.destinationViewController setImageView:imageView];
    }
}

我已经尝试将 FooViewController.imageView 设置为强而不是弱,但问题仍然存在:
@property (nonatomic, strong) UIImageView *imageView;

运行我的调试器,我注意到 FooViewController 中的 imageView 在 prepareForSegue 中正确更新:但随后几行被重新更新为一些新分配的 imageView,@property 图像设置为 nil。我不确定控制流的哪一部分导致了这种情况,因为它发生在用汇编语言编写的行中。

我通过向 FooViewController 添加 UIImage 属性来使我的代码工作:
@property (nonatomic, strong) UIImage *myImage;

并在 BarViewController 中更改 prepareForSegue: 以传递图像而不是 imageView:
// code in BarViewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    if([segue.identifier isEqualToString:@"BarToFooSegue"]){
        NSURL *photoUrl = @"http://www.randurl.com/someImage"; // assume valid url
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:photoUrl]];

        [segue.destinationViewController setMyImage:image];
}

并在 FooViewController 中修改 viewWillAppear:
- (void)viewWillAppear:(BOOL)animated{
    [self.imageView setImage:self.myImage];
}

最佳答案

在设置图像之前调用 [segue.destinationViewController view];,这将导致加载 View 层次结构,然后设置您的导出。

关于iphone - 为什么我的对象没有通过 segue 正确传递?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12453096/

10-11 06:53