this is probably simple but I’m stuck!
Basically I have a parent and child view controller, and I’m trying to pass data from the child to the parent.
//Child VC interface
@protocol ANSearchGetawayFilterDelegate
-(void)selectedCell:(NSString *)cellTitle;
@end
@interface ANSearchGetawayFilterViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
{
NSString* cellTitle;
}
@property (nonatomic, assign) id<ANSearchGetawayFilterDelegate> delegate;
@end
//Child VC implementation
@implementation ANSearchGetawayFilterViewController
@synthesize delegate = _delegate;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
cellTitle = selectedCell.textLabel.text;
[[self delegate] selectedCell:cellTitle];
[self dismissModalViewControllerAnimated:YES];
}
//Parent VC interface
#import "ANSearchGetawayFilterViewController.h"
@interface ANGetawayFilterViewController : UIViewController <ANSearchGetawayFilterDelegate>
{
NSString* _cellText;
}
//Parent VC Implementation
- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// Custom initialization
ANSearchGetawayFilterViewController *search = [[ANSearchGetawayFilterViewController alloc] init];
search.delegate = self;
}
return self;
}
//delegate method
-(void)selectedCell:(NSString *)cellTitle
{
_cellText = cellTitle;
NSLog(@"cell text %@", _cellText);
}
the delegate method is never called and when is NSLog the _cellText else where it comes up as null…what am I doing wrong? Thanks!
You are most likely creating a new instance of
ANSearchGetawayFilterViewControllerwhen you present it and not configuring the delegate on it.When you called
you created an instance of
ANSearchGetawayFilterViewControllerand then set the delegate up correctly, but you never stored this instance ofANSearchGetawayFilterViewControlleranywhere. So later on when you come to present it you call againwhich gives you a completely different instance, which you then need to configure again. For example
To fix update your code to be
I wouldn’t make it an ivar as the likelihood is you will present this viewController momentarily just to select some data and then get rid of it, so it is probably safe to discard it and make a new one each time.