今天我使用MVC来构建一个相册。但我无法在ViewControllerB中获得从ViewControllerA传递的数据,我在这里阅读了这篇文章的链接(在视图控制器之间传递数据),并检查了我所做的所有步骤。
这是ViewControllerA
:中的代码
PhotoViewController *photoVC = [[PhotoViewController alloc] initWithNibName:nil bundle:nil];
photoVC.images = images;
photoVC.index = index;
photoVC.view.backgroundColor = [UIColor lightGrayColor];
[self presentViewController:photoVC animated:YES completion:^{
// code
}];
这是ViewControllerB
:中的代码
@interface PhotoViewController : UIViewController
@property (nonatomic ,retain) NSMutableArray *images;
@property (nonatomic, assign) NSInteger index;
@end
这是.m文件
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@", self.images);
}
但我什么都没有,我不知道我错在哪里,如何纠正??非常感谢。
我认为你不能从实例化你的PhotoViewController
PhotoViewController *photoVC = [[PhotoViewController alloc] initWithNibName:nil bundle:nil];
改为:
PhotoViewController *photoVC = [[PhotoViewController alloc] init];
或者应该将标识符传递给nibName
,否则它怎么能找到要加载的Nib文件?
编辑:您应该将此代码部分放在动画完成块中。当您像以前那样传递数据时,UIViewController
并不是完全实例化的。
[self presentViewController:photoVC animated:YES completion:^{
photoVC.images = images;
photoVC.index = index;
photoVC.view.backgroundColor = [UIColor lightGrayColor];
}];
第2版:原因:
您指定的笔尖文件不会立即加载。它已加载第一次访问视图控制器的视图时。如果你想在加载了所述nib文件之后执行额外的初始化,重写viewDidLoad方法并在那里执行任务。
Storyboard在两个控制器和控制器运行之间相等。
PhotoViewController *photoVC = [[PhotoViewController alloc] initWithNibName:nil bundle:nil];
photoVC.images = images;
photoVC.index = index;
photoVC.view.backgroundColor = [UIColor lightGrayColor];
[self presentViewController:photoVC animated:YES completion:^{
// code
}];