gpt4 book ai didi

iphone - 为什么我的对象没有通过 segue 正确传递?

转载 作者:可可西里 更新时间:2023-11-01 05:14:22 25 4
gpt4 key购买 nike

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

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

@property (nonatomic, weak) UIImageView *imageView;

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

当我运行以下代码并在 FooViewController.imageView.image 上调用 NSLog 时,结果为 nil,并且我的图像不会显示。为什么会这样?

// 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;

并更改 prepareForSegue: 在 BarViewController 中传递图像而不是 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 层次结构,然后设置 socket 。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com