我有两个视图控制器。 ViewControllerA
和ViewcontrollerB
。ViewControllerA
有一个按钮,可以让您ViewControllerB
通过segue。
ViewControllerB
允许用户通过设备相机拍摄照片,并应在ViewcontrollerA
中分配此图像。但是我的应用程序崩溃了。
ViewControllerA
@property (strong, nonatomic) IBOutlet UIImageView *userPicture;
ViewControllerB
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
ViewControllerA *userPhoto=[[ViewControllerA alloc] init];
userPhoto.userPicture.image=chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
它允许Use Photo
按钮和应用在分配拍摄的图像时崩溃。
收到以下错误消息:
[ViewControllerB userPicture]:无法识别的选择器发送到实例 0x14e636160
答案 0 :(得分:3)
您在此行中错误地初始化了另一个ViewControllerA
对象:
ViewControllerA *userPhoto=[[ViewControllerA alloc] init];
您应该实现委托模式。在其中创建协议ViewControllerBDelegate
和方法- (void)imageSelected:(UIImage *)iImage
。
在ViewControllerA
方法中将prepareForSegue:sender:
设置为ViewControllerB的委托,然后在ViewControllerA
中实现上述委托方法方法。从ViewControllerB
开始,只需致电[self.delegate imageSelected: chosenImage]
。
编辑:每个OP请求的代码示例:
第1步:将以下协议添加到ViewControllerB.h
@protocol ViewControllerBDelegate <NSObject>
@required
- (void)imageSelected:(UIImage *)iImage;
@end
第2步:将委托属性添加到ViewControllerB.h
@property (nonatomic, weak) id <ViewControllerBDelegate> delegate;
第3步:在ViewControllerA.m
- (void)prepareForSegue:(UIStoryboardSegue *)iSegue sender:(id)iSender {
ViewControllerB *vcontrollerB = (ViewControllerB *)iSender.destinationViewController;
vcontrollerB.delegate = self;
}
第4步:在ViewControllerB.m
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[picker dismissViewControllerAnimated:YES completion:^{
if (self.delegate && [self.delegate respondsToSelector:@selector(imageSelected:)]) {
[self.delegate imageSelected:chosenImage];
}
}];
}
第5步:在ViewControllerA.m
- (void)imageSelected:(UIImage *)iImage {
self.userPicture.image = iImage;
}
作为旁注,如果不需要从userPicture
外部访问,我宁愿将ViewControllerA
图像视图放在我的实现文件中。