Why is My Application Crashing When I Call a Method in self.parentViewController?
In my code I'm doing the following:
-(void)pushCropImageViewControllerWithDictionary:(NSDictionary *)dictionary {
civc = [[CropImageViewController alloc] init];
[self presentModalViewController:civc animated:YES];
civc.myImage.image = [dictionary objectForKey:UIImagePickerControllerOriginalImage];
}
So I have a modal view in my app. When this modal view dismisses, I want to call a method from the parent view (the view that called pushCropImageViewControllerWithDictionary), like this:
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillAppear:animated];
[(AddNewItemViewController *)self.parentViewController addCroppedPicture:screenshot];
}
But it keeps crashing with the following message:
Terminating app due to uncaught exception开发者_开发问答 'NSInvalidArgumentException', reason: '-[UITabBarController addCroppedPicture:]: unrecognized selector sent to instance 0x4d15930'
Can someone tell me what am I doing wrong? I am including the header for AddNewItemViewController so the selector should be recognized. Can someone give me a hand on how can I do this properly? Thanks.
EDIT: Declaration of addCroppedPicture:
-(void)addCroppedPicture:(UIImage *)image;
The implementation itself is empty so far.
Apparently, self.parentViewController
isn't an instance of AddNewItemViewController
but the tab bar controller. Hence the crash.
The proper solution is to make a delegate:
-(void)pushCropImageViewControllerWithDictionary:(NSDictionary *)dictionary { civc = [[CropImageViewController alloc] init]; civc.delegate = self; [self presentModalViewController:civc animated:YES]; ... }
To send a message back to the delegate:
-(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.delegate addCroppedPicture:screenshot]; }
It's up to you do declare the delegate protocol:
@protocol CropImageDelegate <NSObject> - (void)addCroppedPicture:(UIImage*)image; @end
And add a property for the delegate to CropImageViewController
:
@property (nonatomic, assign) id<CropImageDelegate> delegate;
And finally, make your view controller conform to this delegate protocol.
精彩评论